Skip to content
Verified contractPartialBUSL-1.1

WithdrawHelper

Address0x3a2e9c26fbb53990bafaec0342e38bd2a06f46d3
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 20,000 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
23,332,032
Creation transaction
0xa26dbfca4b…335a261c32

src/utils/WithdrawHelper.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

import {IWithdrawHelper} from "../interfaces/IWithdrawHelper.sol";
import {ISafe, Operation} from "../interfaces/ISafe.sol";
import {IArrakisMetaVaultPrivate} from
    "../interfaces/IArrakisMetaVaultPrivate.sol";
import {IArrakisMetaVault} from "../interfaces/IArrakisMetaVault.sol";
import {BASE, NATIVE_COIN} from "../constants/CArrakis.sol";

import {FullMath} from "@v3-lib-0.8/contracts/FullMath.sol";

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";

/// @title Helper contract to withdraw funds from a vault at any ratio.
contract WithdrawHelper is IWithdrawHelper {
    using Address for address payable;

    /// @inheritdoc IWithdrawHelper
    function withdraw(
        address safe_,
        address vault_,
        uint256 amount0_,
        uint256 amount1_,
        address payable receiver_
    ) external override {
        // #region checks.

        if (msg.sender != safe_) {
            revert Unauthorized();
        }

        // #endregion checks.

        uint256 proportion;
        bytes memory payload;

        // #region get underlying.

        {
            (uint256 total0, uint256 total1) =
                IArrakisMetaVault(vault_).totalUnderlying();

            if (amount0_ > total0 || amount1_ > total1) {
                revert InsufficientUnderlying();
            }

            uint256 proportion0 = amount0_ > 0 ?
                FullMath.mulDiv(amount0_, BASE, total0) : 0;
            uint256 proportion1 = amount1_ > 0 ?
                FullMath.mulDiv(amount1_, BASE, total1) : 0;

            proportion =
                proportion0 > proportion1 ? proportion0 : proportion1;
        }

        // #endregion get underlying.

        // #region balance of safe.

        address token0 = IArrakisMetaVault(vault_).token0();
        address token1 = IArrakisMetaVault(vault_).token1();

        uint256 balance0;
        uint256 balance1;

        if (token0 == NATIVE_COIN) {
            balance0 = safe_.balance;
        } else {
            balance0 = IERC20(token0).balanceOf(safe_);
        }

        if (token1 == NATIVE_COIN) {
            balance1 = safe_.balance;
        } else {
            balance1 = IERC20(token1).balanceOf(safe_);
        }

        // #endregion balance of safe.

        // #region withdraw liquidity.

        {
            payload = abi.encodeWithSelector(
                IArrakisMetaVaultPrivate.withdraw.selector,
                proportion,
                safe_
            );

            bool success = ISafe(safe_).execTransactionFromModule(
                vault_, 0, payload, Operation.Call
            );

            if (!success) {
                revert WithdrawErr();
            }
        }

        // #endregion withdraw liquidity.

        if (token0 == NATIVE_COIN) {
            balance0 = safe_.balance - balance0;
        } else {
            balance0 = IERC20(token0).balanceOf(safe_) - balance0;
        }

        if (token1 == NATIVE_COIN) {
            balance1 = safe_.balance - balance1;
        } else {
            balance1 = IERC20(token1).balanceOf(safe_) - balance1;
        }

        // #region transfer amount0 and amount1 to receiver.

        if (amount0_ > 0) {
            uint256 amountToTransfer =
                amount0_ > balance0 ? balance0 : amount0_;
            balance0 -= amountToTransfer;
            bool success;
            bytes memory returnData;
            if (token0 == NATIVE_COIN) {
                success = ISafe(safe_).execTransactionFromModule(
                    receiver_, amountToTransfer, "", Operation.Call
                );
            } else {
                payload = abi.encodeWithSelector(
                    IERC20.transfer.selector,
                    receiver_,
                    amountToTransfer
                );

                (success, returnData) = ISafe(safe_)
                    .execTransactionFromModuleReturnData(
                    token0, 0, payload, Operation.Call
                );
            }

            if (!success) {
                revert Transfer0Err();
            }

            if (returnData.length > 0) {
                bool transferSuccessful =
                    abi.decode(returnData, (bool));

                if (!transferSuccessful) {
                    revert Transfer0Err();
                }
            }
        }

        if (amount1_ > 0) {
            uint256 amountToTransfer =
                amount1_ > balance1 ? balance1 : amount1_;
            balance1 -= amountToTransfer;
            bool success;
            bytes memory returnData;
            if (token1 == NATIVE_COIN) {
                success = ISafe(safe_).execTransactionFromModule(
                    receiver_, amountToTransfer, "", Operation.Call
                );
            } else {
                payload = abi.encodeWithSelector(
                    IERC20.transfer.selector,
                    receiver_,
                    amountToTransfer
                );

                (success, returnData) = ISafe(safe_)
                    .execTransactionFromModuleReturnData(
                    token1, 0, payload, Operation.Call
                );
            }

            if (!success) {
                revert Transfer1Err();
            }

            if (returnData.length > 0) {
                bool transferSuccessful =
                    abi.decode(returnData, (bool));

                if (!transferSuccessful) {
                    revert Transfer1Err();
                }
            }
        }

        // #endregion transfer amount0 and amount1 to receiver.

        // #region check if safe is a depositor and whitelist it if neccesary.

        bool isDepositor;

        {
            address[] memory depositors =
                IArrakisMetaVaultPrivate(vault_).depositors();

            uint256 length = depositors.length;

            for (uint256 i = 0; i < length;) {
                if (depositors[i] == safe_) {
                    isDepositor = true;
                    break;
                }

                unchecked {
                    i += 1;
                }
            }
        }

        if (!isDepositor) {
            address[] memory depositors = new address[](1);
            depositors[0] = safe_;

            payload = abi.encodeWithSelector(
                IArrakisMetaVaultPrivate.whitelistDepositors.selector,
                depositors
            );

            bool success = ISafe(safe_).execTransactionFromModule(
                vault_, 0, payload, Operation.Call
            );

            if (!success) {
                revert WhitelistDepositorErr();
            }
        }

        // #endregion check if safe is a depositor and whitelist it if neccesary.

        // #region approve module.

        uint256 value;

        {
            address module =
                address(IArrakisMetaVault(vault_).module());

            if (balance0 > 0) {
                if (token0 != NATIVE_COIN) {
                    payload = abi.encodeWithSelector(
                        IERC20.approve.selector, module, balance0
                    );

                    (bool success, bytes memory returnData) = ISafe(
                        safe_
                    ).execTransactionFromModuleReturnData(
                        token0, 0, payload, Operation.Call
                    );

                    if (!success) {
                        revert Approval0Err();
                    }

                    if (returnData.length > 0) {
                        bool transferSuccessful =
                            abi.decode(returnData, (bool));

                        if (!transferSuccessful) {
                            revert Approval0Err();
                        }
                    }
                } else {
                    value = balance0;
                }
            }

            if (balance1 > 0) {
                if (token1 != NATIVE_COIN) {
                    payload = abi.encodeWithSelector(
                        IERC20.approve.selector, module, balance1
                    );

                    (bool success, bytes memory returnData) = ISafe(
                        safe_
                    ).execTransactionFromModuleReturnData(
                        token1, 0, payload, Operation.Call
                    );

                    if (!success) {
                        revert Approval1Err();
                    }

                    if (returnData.length > 0) {
                        bool transferSuccessful =
                            abi.decode(returnData, (bool));

                        if (!transferSuccessful) {
                            revert Approval1Err();
                        }
                    }
                } else {
                    value = balance1;
                }
            }
        }

        // #endregion approve module.

        // #region deposit left over.

        if (balance0 > 0 || balance1 > 0) {
            payload = abi.encodeWithSelector(
                IArrakisMetaVaultPrivate.deposit.selector,
                balance0,
                balance1
            );

            bool success = ISafe(safe_).execTransactionFromModule(
                vault_, value, payload, Operation.Call
            );

            if (!success) {
                revert DepositErr();
            }
        }

        // #endregion deposit left over.
    }
}

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
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 amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` 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 amount) external returns (bool);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/openzeppelin-contracts/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

lib/v3-lib-0.8/contracts/FullMath.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(a, b, not(0))
                prod0 := mul(a, b)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                require(denominator > 0);
                assembly {
                    result := div(prod0, denominator)
                }
                return result;
            }

            // Make sure the result is less than 2**256.
            // Also prevents denominator == 0
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            // EDIT for 0.8 compatibility:
            // see: https://ethereum.stackexchange.com/questions/96642/unary-operator-cannot-be-applied-to-type-uint256
            uint256 twos = denominator & (~denominator + 1);

            // Divide denominator by power of two
            assembly {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

            // Invert denominator mod 2**256
            // Now that denominator is an odd number, it has an inverse
            // modulo 2**256 such that denominator * inv = 1 mod 2**256.
            // Compute the inverse by starting with a seed that is correct
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use Newton-Raphson iteration to improve the precision.
            // Thanks to Hensel's lifting lemma, this also works in modular
            // arithmetic, doubling the correct bits in each step.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // inverse mod 2**256

            // Because the division is now exact we can divide by multiplying
            // with the modular inverse of denominator. This will give us the
            // correct result modulo 2**256. Since the precoditions guarantee
            // that the outcome is less than 2**256, this is the final result.
            // We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inv;
            return result;
        }
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        result = mulDiv(a, b, denominator);
        if (mulmod(a, b, denominator) > 0) {
            require(result < type(uint256).max);
            result++;
        }
    }
}

src/constants/CArrakis.sol

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

uint256 constant MINIMUM_LIQUIDITY = 10 ** 3;
uint256 constant BASE = 1e18;
uint24 constant PIPS = 1_000_000;
uint24 constant TEN_PERCENT = 100_000;
uint256 constant WEEK = 604_800;
address constant NATIVE_COIN =
    0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint8 constant NATIVE_COIN_DECIMALS = 18;

src/interfaces/IArrakisLPModule.sol

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

import {IERC20Metadata} from
    "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IArrakisMetaVault} from "./IArrakisMetaVault.sol";
import {IOracleWrapper} from "./IOracleWrapper.sol";

/// @title Liquidity providing module interface.
/// @author Arrakis Finance
/// @notice Module interfaces, modules are implementing differents strategies that an
/// arrakis module can use.
interface IArrakisLPModule {
    // #region errors.

    /// @dev triggered when an address that should not
    /// be zero is equal to address zero.
    error AddressZero();

    /// @dev triggered when the caller is different than
    /// the metaVault that own this module.
    error OnlyMetaVault(address caller, address metaVault);

    /// @dev triggered when the caller is different than
    /// the manager defined by the metaVault.
    error OnlyManager(address caller, address manager);

    /// @dev triggered if proportion of minting or burning is
    /// zero.
    error ProportionZero();

    /// @dev triggered if during withdraw more than 100% of the
    /// position.
    error ProportionGtBASE();

    /// @dev triggered when manager want to set his more
    /// earned by the position than 100% of fees earned.
    error NewFeesGtPIPS(uint256 newFees);

    /// @dev triggered when manager is setting the same fees
    /// that already active.
    error SameManagerFee();

    /// @dev triggered when inits values are zeros.
    error InitsAreZeros();

    /// @dev triggered when pause/unpaused function is
    /// called by someone else than guardian.
    error OnlyGuardian();

    // #endregion errors.

    // #region events.

    /// @notice Event describing a withdrawal of participation by an user inside this module.
    /// @dev withdraw action can be indexed by receiver.
    /// @param receiver address that will receive the tokens withdrawn.
    /// @param proportion percentage of the current position that user want to withdraw.
    /// @param amount0 amount of token0 send to "receiver" due to withdraw action.
    /// @param amount1 amount of token1 send to "receiver" due to withdraw action.
    event LogWithdraw(
        address indexed receiver,
        uint256 proportion,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Event describing a manager fee withdrawal.
    /// @param manager address of the manager that will fees earned due to his fund management.
    /// @param amount0 amount of token0 that manager has earned and will be transfered.
    /// @param amount1 amount of token1 that manager has earned and will be transfered.
    event LogWithdrawManagerBalance(
        address manager, uint256 amount0, uint256 amount1
    );

    /// @notice Event describing manager set his fees.
    /// @param oldFee fees share that have been taken by manager.
    /// @param newFee fees share that have been taken by manager.
    event LogSetManagerFeePIPS(uint256 oldFee, uint256 newFee);

    // #endregion events.

    /// @notice function used to pause the module.
    /// @dev only callable by guardian
    function pause() external;

    /// @notice function used to unpause the module.
    /// @dev only callable by guardian
    function unpause() external;

    /// @notice function used to initialize the module
    /// when a module switch happen
    /// @param data_ bytes that contain information to initialize
    /// the position.
    function initializePosition(bytes calldata data_) external;

    /// @notice function used by metaVault to withdraw tokens from the strategy.
    /// @param receiver_ address that will receive tokens.
    /// @param proportion_ the proportion of the total position that need to be withdrawn.
    /// @return amount0 amount of token0 withdrawn.
    /// @return amount1 amount of token1 withdrawn.
    function withdraw(
        address receiver_,
        uint256 proportion_
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice function used by metaVault or manager to get manager fees.
    /// @return amount0 amount of token0 sent to manager.
    /// @return amount1 amount of token1 sent to manager.
    function withdrawManagerBalance()
        external
        returns (uint256 amount0, uint256 amount1);

    /// @notice function used to set manager fees.
    /// @param newFeePIPS_ new fee that will be applied.
    function setManagerFeePIPS(uint256 newFeePIPS_) external;

    // #region view functions.

    /// @notice function used to get metaVault as IArrakisMetaVault.
    /// @return metaVault that implement IArrakisMetaVault.
    function metaVault() external view returns (IArrakisMetaVault);

    /// @notice function used to get the address that can pause the module.
    /// @return guardian address of the pauser.
    function guardian() external view returns (address);

    /// @notice function used to get manager token0 balance.
    /// @dev amount of fees in token0 that manager have not taken yet.
    /// @return managerBalance0 amount of token0 that manager earned.
    function managerBalance0() external view returns (uint256);

    /// @notice function used to get manager token1 balance.
    /// @dev amount of fees in token1 that manager have not taken yet.
    /// @return managerBalance1 amount of token1 that manager earned.
    function managerBalance1() external view returns (uint256);

    /// @notice function used to get manager fees.
    /// @return managerFeePIPS amount of token1 that manager earned.
    function managerFeePIPS() external view returns (uint256);

    /// @notice function used to get token0 as IERC20Metadata.
    /// @return token0 as IERC20Metadata.
    function token0() external view returns (IERC20Metadata);

    /// @notice function used to get token1 as IERC20Metadata.
    /// @return token1 as IERC20Metadata.
    function token1() external view returns (IERC20Metadata);

    /// @notice function used to get the initial amounts needed to open a position.
    /// @return init0 the amount of token0 needed to open a position.
    /// @return init1 the amount of token1 needed to open a position.
    function getInits()
        external
        view
        returns (uint256 init0, uint256 init1);

    /// @notice function used to get the amount of token0 and token1 sitting
    /// on the position.
    /// @return amount0 the amount of token0 sitting on the position.
    /// @return amount1 the amount of token1 sitting on the position.
    function totalUnderlying()
        external
        view
        returns (uint256 amount0, uint256 amount1);

    /// @notice function used to get the amounts of token0 and token1 sitting
    /// on the position for a specific price.
    /// @param priceX96_ price at which we want to simulate our tokens composition
    /// @return amount0 the amount of token0 sitting on the position for priceX96.
    /// @return amount1 the amount of token1 sitting on the position for priceX96.
    function totalUnderlyingAtPrice(uint160 priceX96_)
        external
        view
        returns (uint256 amount0, uint256 amount1);

    /// @notice function used to validate if module state is not manipulated
    /// before rebalance.
    /// @param oracle_ oracle that will used to check internal state.
    /// @param maxDeviation_ maximum deviation allowed.
    function validateRebalance(
        IOracleWrapper oracle_,
        uint24 maxDeviation_
    ) external view;

    // #endregion view function.
}

src/interfaces/IArrakisMetaVault.sol

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

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

/// @title IArrakisMetaVault
/// @notice IArrakisMetaVault is a vault that is able to invest dynamically deposited
/// tokens into protocols through his module.
interface IArrakisMetaVault {
    // #region errors.

    /// @dev triggered when an address that should not
    /// be zero is equal to address zero.
    error AddressZero(string property);

    /// @dev triggered when the caller is different than
    /// the manager.
    error OnlyManager(address caller, address manager);

    /// @dev triggered when a low level call failed during
    /// execution.
    error CallFailed();

    /// @dev triggered when manager try to set the active
    /// module as active.
    error SameModule();

    /// @dev triggered when owner of the vault try to set the
    /// manager with the current manager.
    error SameManager();

    /// @dev triggered when all tokens withdrawal has been done
    /// during a switch of module.
    error ModuleNotEmpty(uint256 amount0, uint256 amount1);

    /// @dev triggered when owner try to whitelist a module
    /// that has been already whitelisted.
    error AlreadyWhitelisted(address module);

    /// @dev triggered when owner try to blacklist a module
    /// that has not been whitelisted.
    error NotWhitelistedModule(address module);

    /// @dev triggered when owner try to blacklist the active module.
    error ActiveModule();

    /// @dev triggered during vault creation if token0 address is greater than
    /// token1 address.
    error Token0GtToken1();

    /// @dev triggered during vault creation if token0 address is equal to
    /// token1 address.
    error Token0EqToken1();

    /// @dev triggered when whitelisting action is occuring and module's beacon
    /// is not whitelisted on module registry.
    error NotWhitelistedBeacon();

    /// @dev triggered when guardian of the whitelisting module is different than
    /// the guardian of the registry.
    error NotSameGuardian();

    /// @dev triggered when a function logic is not implemented.
    error NotImplemented();

    /// @dev triggered when two arrays suppposed to have the same length, have different length.
    error ArrayNotSameLength();

    /// @dev triggered when function is called by someone else than the owner.
    error OnlyOwner();

    /// @dev triggered when setModule action try to remove funds.
    error WithdrawNotAllowed();

    /// @dev triggered when setModule function end without
    /// initiliazePosition call.
    error PositionNotInitialized();

    /// @dev triggered when the first external call of setModule function
    /// isn't InitializePosition function.
    error NotPositionInitializationCall();

    // #endregion errors.

    // #region events.

    /// @notice Event describing a manager fee withdrawal.
    /// @param amount0 amount of token0 that manager has earned and will be transfered.
    /// @param amount1 amount of token1 that manager has earned and will be transfered.
    event LogWithdrawManagerBalance(uint256 amount0, uint256 amount1);

    /// @notice Event describing owner setting the manager.
    /// @param manager address of manager that will manage the portfolio.
    event LogSetManager(address manager);

    /// @notice Event describing manager setting the module.
    /// @param module address of the new active module.
    /// @param payloads data payloads for initializing positions on the new module.
    event LogSetModule(address module, bytes[] payloads);

    /// @notice Event describing default module that the vault will be initialized with.
    /// @param module address of the default module.
    event LogSetFirstModule(address module);

    /// @notice Event describing list of modules that has been whitelisted by owner.
    /// @param modules list of addresses corresponding to new modules now available
    /// to be activated by manager.
    event LogWhiteListedModules(address[] modules);

    /// @notice Event describing whitelisted of the first module during vault creation.
    /// @param module default activation.
    event LogWhitelistedModule(address module);

    /// @notice Event describing blacklisting action of modules by owner.
    /// @param modules list of addresses corresponding to old modules that has been
    /// blacklisted.
    event LogBlackListedModules(address[] modules);

    // #endregion events.

    /// @notice function used to initialize default module.
    /// @param module_ address of the default module.
    function initialize(address module_) external;

    /// @notice function used to set module
    /// @param module_ address of the new module
    /// @param payloads_ datas to initialize/rebalance on the new module
    function setModule(
        address module_,
        bytes[] calldata payloads_
    ) external;

    /// @notice function used to whitelist modules that can used by manager.
    /// @param beacons_ array of beacons addresses to use for modules creation.
    /// @param data_ array of payload to use for modules creation.
    function whitelistModules(
        address[] calldata beacons_,
        bytes[] calldata data_
    ) external;

    /// @notice function used to blacklist modules that can used by manager.
    /// @param modules_ array of module addresses to be blacklisted.
    function blacklistModules(address[] calldata modules_) external;

    // #region view functions.

    /// @notice function used to get the list of modules whitelisted.
    /// @return modules whitelisted modules addresses.
    function whitelistedModules()
        external
        view
        returns (address[] memory modules);

    /// @notice function used to get the amount of token0 and token1 sitting
    /// on the position.
    /// @return amount0 the amount of token0 sitting on the position.
    /// @return amount1 the amount of token1 sitting on the position.
    function totalUnderlying()
        external
        view
        returns (uint256 amount0, uint256 amount1);

    /// @notice function used to get the amounts of token0 and token1 sitting
    /// on the position for a specific price.
    /// @param priceX96 price at which we want to simulate our tokens composition
    /// @return amount0 the amount of token0 sitting on the position for priceX96.
    /// @return amount1 the amount of token1 sitting on the position for priceX96.
    function totalUnderlyingAtPrice(uint160 priceX96)
        external
        view
        returns (uint256 amount0, uint256 amount1);

    /// @notice function used to get the initial amounts needed to open a position.
    /// @return init0 the amount of token0 needed to open a position.
    /// @return init1 the amount of token1 needed to open a position.
    function getInits()
        external
        view
        returns (uint256 init0, uint256 init1);

    /// @notice function used to get the address of token0.
    function token0() external view returns (address);

    /// @notice function used to get the address of token1.
    function token1() external view returns (address);

    /// @notice function used to get manager address.
    function manager() external view returns (address);

    /// @notice function used to get module used to
    /// open/close/manager a position.
    function module() external view returns (IArrakisLPModule);

    /// @notice function used to get module registry.
    /// @return registry address of module registry.
    function moduleRegistry()
        external
        view
        returns (address registry);

    // #endregion view functions.
}

src/interfaces/IArrakisMetaVaultPrivate.sol

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

interface IArrakisMetaVaultPrivate {
    // #region errors.

    error MintZero();
    error BurnZero();
    error BurnOverflow();
    error DepositorAlreadyWhitelisted();
    error NotAlreadyWhitelistedDepositor();
    error OnlyDepositor();

    // #endregion errors.

    // #region events.

    /// @notice Event describing a deposit done by an user inside this vault.
    /// @param amount0 amount of token0 needed to increase the portfolio of "proportion" percent.
    /// @param amount1 amount of token1 needed to increase the portfolio of "proportion" percent.
    event LogDeposit(uint256 amount0, uint256 amount1);

    /// @notice Event describing a withdrawal of participation by an user inside this vault.
    /// @param proportion percentage of the current position that user want to withdraw.
    /// @param amount0 amount of token0 withdrawn due to withdraw action.
    /// @param amount1 amount of token1 withdrawn due to withdraw action.
    event LogWithdraw(
        uint256 proportion, uint256 amount0, uint256 amount1
    );

    /// @notice Event describing the whitelist of fund depositor.
    /// @param depositors list of address that are granted to depositor role.
    event LogWhitelistDepositors(address[] depositors);

    /// @notice Event describing the blacklist of fund depositor.
    /// @param depositors list of address who depositor role is revoked.
    event LogBlacklistDepositors(address[] depositors);

    // #endregion events.

    /// @notice function used to deposit tokens or expand position inside the
    /// inherent strategy.
    /// @param amount0_ amount of token0 need to increase the position by proportion_;
    /// @param amount1_ amount of token1 need to increase the position by proportion_;
    function deposit(
        uint256 amount0_,
        uint256 amount1_
    ) external payable;

    /// @notice function used to withdraw tokens or position contraction of the
    /// underpin strategy.
    /// @param proportion_ the proportion of position contraction.
    /// @param receiver_ the address that will receive withdrawn tokens.
    /// @return amount0 amount of token0 returned.
    /// @return amount1 amount of token1 returned.
    function withdraw(
        uint256 proportion_,
        address receiver_
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice function used to whitelist depositors.
    /// @param depositors_ list of address that will be granted to depositor role.
    function whitelistDepositors(address[] calldata depositors_)
        external;

    /// @notice function used to blacklist depositors.
    /// @param depositors_ list of address who depositor role will be revoked.
    function blacklistDepositors(address[] calldata depositors_)
        external;

    /// @notice function used to get the list of depositors.
    /// @return depositors list of address granted to depositor role.
    function depositors() external view returns (address[] memory);
}

src/interfaces/IOracleWrapper.sol

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

interface IOracleWrapper {
    // #region errors.

    error AddressZero();
    error DecimalsToken0Zero();
    error DecimalsToken1Zero();

    // #endregion errors.

    /// @notice function used to get price0.
    /// @return price0 price of token0/token1.
    function getPrice0() external view returns (uint256 price0);

    /// @notice function used to get price1.
    /// @return price1 price of token1/token0.
    function getPrice1() external view returns (uint256 price1);
}

src/interfaces/ISafe.sol

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

enum Operation {
    Call,
    DelegateCall
}

interface ISafe {
    /// @dev Allows a Module to execute a Safe transaction without any further confirmations.
    /// @param to Destination address of module transaction.
    /// @param value Ether value of module transaction.
    /// @param data Data payload of module transaction.
    /// @param operation Operation type of module transaction.
    function execTransactionFromModule(
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation
    ) external returns (bool success);

    function execTransactionFromModuleReturnData(
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation
    ) external returns (bool success, bytes memory returnData);

    function disableModule(
        address prevModule,
        address module
    ) external;

    function getModulesPaginated(
        address start,
        uint256 pageSize
    ) external view returns (address[] memory array, address next);
}

src/interfaces/IWithdrawHelper.sol

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

interface IWithdrawHelper {

    // #region errors.

    /// @notice Error emitted when the withdraw try to
    /// withdraw more than the funds sitting on the vault.
    error InsufficientUnderlying();
    /// @notice Error emitted when the caller is not the safe.
    error Unauthorized();
    /// @notice Error emitted when the withdraw fails.
    error WithdrawErr();
    /// @notice Error emitted when whitelisting safe as depositor fails.
    error WhitelistDepositorErr();
    /// @notice Error emitted when transfering token0 to receiver fails.
    error Transfer0Err();
    /// @notice Error emitted when transfering token1 to receiver fails.
    error Transfer1Err();
    /// @notice Error emitted when approving module to use token0 fails.
    error Approval0Err();
    /// @notice Error emitted when approving module to use token1 fails.
    error Approval1Err();
    /// @notice Error emitted when depositing through the safe fails.
    error DepositErr();

    // #endregion errors.

    // #region functions.

    /// @notice Withdraws the funds from the vault at any ratio.
    /// @param safe_ The address of the safe that owns the vault.
    /// @param vault_ The address of the vault to withdraw the funds from.
    /// @param amount0_ The amount of token0 to withdraw.
    /// @param amount1_ The amount of token1 to withdraw.
    /// @param receiver_ The address that will receive the funds.
    function withdraw(
        address safe_,
        address vault_,
        uint256 amount0_,
        uint256 amount1_,
        address payable receiver_
    ) external;

    // #endregion functions.
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 20000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@solady/contracts/=lib/solady/src/",
    "@create3/contracts/=lib/create3/contracts/",
    "@v3-lib-0.8/contracts/=lib/v3-lib-0.8/contracts/",
    "forge-std/=lib/forge-std/src/",
    "@valantis-hot/contracts/=lib/valantis-hot/src/",
    "@valantis-core/contracts/=lib/valantis-hot/lib/valantis-core/src/",
    "@valantis-hot/contracts-test/=lib/valantis-hot/test/",
    "@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "@uniswap/permit2/=lib/v4-periphery/lib/permit2/",
    "@pancakeswap/v4-core/=lib/infinity-core/",
    "lib/infinity-core/:@openzeppelin/contracts/=/lib/infinity-core/lib/openzeppelin-contracts/contracts/",
    "@ensdomains/=lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
    "@uniswap/v3-core/=lib/valantis-hot/lib/v3-core/",
    "@uniswap/v3-periphery/=lib/valantis-hot/lib/v3-periphery/",
    "create3/=lib/create3/contracts/",
    "doppler-hook/=lib/doppler-hook/src/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/forge-gas-snapshot/src/",
    "halmos-cheatcodes/=lib/infinity-core/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-periphery/lib/v4-core/node_modules/hardhat/",
    "infinity-core/=lib/infinity-core/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "pancake-create3-factory/=lib/infinity-core/lib/pancake-create3-factory/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "solady/=lib/solady/",
    "solmate/=lib/infinity-core/lib/solmate/",
    "v3-core/=lib/valantis-hot/lib/v3-core/contracts/",
    "v3-lib-0.8/=lib/v3-lib-0.8/contracts/",
    "v3-periphery/=lib/valantis-hot/lib/v3-periphery/contracts/",
    "v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/",
    "valantis-core/=lib/valantis-hot/lib/valantis-core/",
    "valantis-hot/=lib/valantis-hot/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.