Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/strategy/CurveStrategy.sol": {
"content": "// SPDX-License-Identifier: LicenseRef-CICADA-Proprietary
// SPDX-FileCopyrightText: (c) 2024 Cicada Software, CICADA DMCC. All rights reserved.
pragma solidity ^0.8.28;
/* ====== EXTERNAL IMPORTS ====== */
import {SafeERC20} from "@openzeppelin-contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin-contracts/token/ERC20/IERC20.sol";
import {Ownable} from "@openzeppelin-contracts/access/Ownable.sol";
import {ERC165} from "@openzeppelin-contracts/utils/introspection/ERC165.sol";
/* ====== INTERFACES IMPORTS ====== */
import {ICurveStrategy, IStrategy} from "../interfaces/ICurveStrategy.sol";
import {SwapParams} from "../interfaces/ICurveQuoter.sol";
import {ICurveRouter} from "../interfaces/curve/IRouter.sol";
/* ====== CONTRACTS IMPORTS ====== */
import {Vault} from "../Vault.sol";
import {Enums, Exact} from "../lib/Common.sol";
import {CurveQuoter} from "../mux/CurveQuoter.sol";
/**
* @title CurveStrategy
* @notice This contract is a router for Curve, that creates unified interface
* for Vault contracts to interact with Curve protocol
*/
contract CurveStrategy is ICurveStrategy, CurveQuoter, Ownable, ERC165 {
using SafeERC20 for IERC20;
/* ======== ERRORS ======== */
/// @notice CurveStrategy only supports Enums.Flavor.Curve
error InvalidFlavor();
/* ======== CONSTRUCTOR AND INIT ======== */
/**
* @notice Initializes the Strategy with the provided Curve Router.
* @param _router Address of the Curve Router NG.
*/
constructor(address _router) CurveQuoter(_router) Ownable(msg.sender) {}
/* ======== EXTERNAL/PUBLIC ======== */
/// @inheritdoc IStrategy
function buy(uint256 amountOutBase, uint256 amountInMaxQuote, Enums.Flavor flavor, bytes calldata flavorParams)
external
{
Vault vault = Vault(payable(msg.sender));
IERC20 quoteToken = vault.quoteToken();
IERC20 baseToken = vault.baseToken();
Enums.Direction direction = Enums.Direction.QuoteToBase;
_buyOrSell(
address(quoteToken),
address(baseToken),
address(vault),
amountOutBase,
amountInMaxQuote,
direction,
flavor,
flavorParams
);
}
/// @inheritdoc IStrategy
function sell(uint256 amountInBase, uint256 amountOutMinQuote, Enums.Flavor flavor, bytes calldata flavorParams)
external
{
Vault vault = Vault(payable(msg.sender));
IERC20 baseToken = vault.baseToken();
IERC20 quoteToken = vault.quoteToken();
Enums.Direction direction = Enums.Direction.BaseToQuote;
_buyOrSell(
address(baseToken),
address(quoteToken),
address(vault),
amountInBase,
amountOutMinQuote,
direction,
flavor,
flavorParams
);
}
/// @notice quote for trades for specific vault
function quote(address vault, Exact exactType, uint256 baseTokenAmount, SwapParams[] memory swapParams)
external
view
returns (uint256 baseAmount, uint256 quoteAmount)
{
Enums.Direction direction = exactType == Exact.Out ? Enums.Direction.QuoteToBase : Enums.Direction.BaseToQuote;
_validateSwapParams(swapParams, direction, vault);
(uint256 amountIn, uint256 amountOut) = quote(exactType, baseTokenAmount, swapParams);
(baseAmount, quoteAmount) = _isBuy(direction) ? (amountOut, amountIn) : (amountIn, amountOut);
}
/* ======== INTERNAL ======== */
/**
* @notice Executes a buy or sell operation by swapping a specified amount of tokens
* @param tokenIn The address of the token to swap from
* @param recipient The address of the recipient of the swapped tokens
* @param baseTokenAmount The amount of base tokens to swap
* @param quoteTokenAmount The amount of quote tokens to swap
* @param direction The direction of the swap
* @param flavor The flavor of the strategy
* @param flavorParams encoded path parameters in Cicada's proprietary format
*/
function _buyOrSell(
address tokenIn,
address,
address recipient,
uint256 baseTokenAmount,
uint256 quoteTokenAmount,
Enums.Direction direction,
Enums.Flavor flavor,
bytes calldata flavorParams
) internal {
if (baseTokenAmount == 0) revert ZeroAmount();
if (quoteTokenAmount == 0) revert ZeroAmount();
if (flavor != Enums.Flavor.Curve) revert InvalidFlavor();
(uint256 amountToSpend, uint256 amountToReceive) =
_isBuy(direction) ? (quoteTokenAmount, baseTokenAmount) : (baseTokenAmount, quoteTokenAmount);
IERC20(tokenIn).safeTransferFrom(recipient, address(this), amountToSpend);
(SwapParams[] memory swapParams) = abi.decode(flavorParams, (SwapParams[]));
_validateSwapParams(swapParams, direction, recipient);
(address[11] memory route, address[5] memory pools) = _buildRoute(swapParams);
uint256[5][5] memory _swapParams = _buildSwapParams(swapParams);
ICurveRouter router = ICurveRouter(payable(ROUTER));
IERC20(tokenIn).forceApprove(address(router), amountToSpend);
ICurveRouter(payable(ROUTER)).exchange(route, _swapParams, amountToSpend, amountToReceive, pools, recipient);
if (_isBuy(direction)) _returnUnspentTokens(tokenIn, recipient);
}
/// @notice Returns the unspent tokens on BUY direction to the vault
/// @param token the address of the token (quoteToken)
/// @param recipient the address of the recipient (vault)
function _returnUnspentTokens(address token, address recipient) internal {
uint256 amount = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(recipient, amount);
}
/// @inheritdoc ICurveStrategy
function withdraw(address token, address recipient) external onlyOwner {
if (token == address(0)) {
uint256 amount = address(this).balance;
payable(recipient).transfer(amount);
} else {
uint256 amount = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(recipient, amount);
}
}
/* ======== VIEW ======== */
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) {
return interfaceId == type(ICurveStrategy).interfaceId || super.supportsInterface(interfaceId);
}
}
"
},
"dependencies/@openzeppelin-contracts-5.2.0/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
"
},
"dependencies/@openzeppelin-contracts-5.2.0/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
"
},
"dependencies/@openzeppelin-contracts-5.2.0/access/Ownable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
"
},
"dependencies/@openzeppelin-contracts-5.2.0/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
"
},
"src/interfaces/ICurveStrategy.sol": {
"content": "// SPDX-License-Identifier: LicenseRef-CICADA-Proprietary
// SPDX-FileCopyrightText: (c) 2024 Cicada Software, CICADA DMCC. All rights reserved.
pragma solidity ^0.8.29;
import {IStrategy} from "./IStrategy.sol";
import {Exact} from "../lib/Common.sol";
import {ICurveQuoter, SwapParams} from "./ICurveQuoter.sol";
interface ICurveStrategy is IStrategy, ICurveQuoter {
/**
* @notice Withdraws a specified amount of a given token from the Vault.
* @notice This function can only be called by an owner account, representing the deployer address or emergency address of the funds.
* @notice Pass zero address (0x0000000000000000000000000000000000000000) to withdraw native token (ETH).
* @dev Allows the funds' owner to withdraw baseToken, quoteToken, or recover any other tokens (e.g., mistakenly sent) from the Vault.
* @param token The ERC20 token to withdraw. If the address is zero, withdraw native token (ETH).
* @param recipient The address to transfer the token to.
*/
function withdraw(address token, address recipient) external;
/**
* @notice Quotes the amount of tokens to swap for a given vault and direction
* @param vault address of the vault (required for validation)
* @param exactType type of the exact amount
* @param amount amount of tokens to swap
* @param swapParams array of swap parameters
* @return baseAmount amount of base tokens to swap
* @return quoteAmount amount of quote tokens to receive
*/
function quote(address vault, Exact exactType, uint256 amount, SwapParams[] memory swapParams)
external
view
returns (uint256 baseAmount, uint256 quoteAmount);
}
"
},
"src/interfaces/ICurveQuoter.sol": {
"content": "// SPDX-License-Identifier: LicenseRef-CICADA-Proprietary
// SPDX-FileCopyrightText: (c) 2024 Cicada Software, CICADA DMCC. All rights reserved.
pragma solidity ^0.8.29;
import {IStrategy} from "./IStrategy.sol";
import {Exact} from "../lib/Common.sol";
/// @notice https://docs.curve.finance/router/CurveRouterNG/#_swap_params
enum PoolType {
Forbidden, // Not introduced in Curve Docs
Stable, // 1 Stable pools using the Stableswap algorithm // TODO: add this
Twocrypto, // 2 Two-coin Crypto pools using the Cryptoswap algorithm // TODO: add this
Tricrypto, // 3 Tricrypto pools with three coins using the Cryptoswap algorithm
Llamma // 4 LLAMMA pools, typically used in crvUSD and lending markets // TODO: add this
}
/// @notice https://docs.curve.finance/router/CurveRouterNG/#_swap_type
enum SwapType {
Forbidden, // Not introduced in Curve Docs
Standard, // 1 Standard token exchange
Underlying, // 2 Underlying token exchange_underlying // TODO: add this
UnderlyingZap, // 3 Underlying exchange via zap for factory stable metapools and crypto-meta pools (exchange_underlying for stable, exchange in zap for crypto) // TODO: add this
CoinToLP, // 4 Coin to LP token "exchange" (effectively add_liquidity) // TODO: add this
LendingPoolUnderlyingCoinToLP, // 5 Lending pool underlying coin to LP token "exchange" (effectively add_liquidity) // TODO: add this
LPTokenToCoin, // 6 LP token to coin "exchange" (effectively remove_liquidity_one_coin) // TODO: add this
LPTokenToLendingOrFakePoolUnderlyingCoin, // 7 LP token to lending or fake pool underlying coin "exchange" (effectively remove_liquidity_one_coin) // TODO: add this
SpecializedSwaps, // 8 Specialized swaps like ETH <-> WETH, ETH -> stETH or frxETH, and cross-liquidity between staked tokens (e.g., stETH <-> wstETH, frxETH <-> sfrxETH) // TODO: add this
SNXRelatedSwaps // 9 SNX-related swaps (e.g., sUSD, sEUR, sETH, sBTC) // TODO: add this
}
/// @notice SwapParams is a struct that contains the parameters for a swap
/// @param pool - the address of the pool
/// @param tokenInIndex - the index of the token in the pool
/// @param tokenOutIndex - the index of the token in the pool
/// @param poolType - the type of the pool
/// @param coinsInPool - number of coins in the pool
struct SwapParams {
address pool;
uint8 tokenInIndex;
uint8 tokenOutIndex;
PoolType poolType;
uint8 coinsInPool;
}
interface ICurveQuoter {
/// @notice The address of the Curve Router NG (https://github.com/curvefi/curve-router-ng)
function ROUTER() external view returns (address);
/**
* @notice Quotes the amount of tokens to swap for a given direction and pools
* @param exactType type of the exact amount
* @param amount amount of tokens to swap
* @param swapParams array of swap parameters
* @return amountIn amount of tokens to swap
* @return amountOut amount of tokens to receive
*/
function quote(Exact exactType, uint256 amount, SwapParams[] memory swapParams)
external
view
returns (uint256 amountIn, uint256 amountOut);
}
"
},
"src/interfaces/curve/IRouter.sol": {
"content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
interface ICurveRouter {
function exchange(
address[11] memory route,
uint256[5][5] memory swap_params,
uint256 amount,
uint256 min_dy,
address[5] memory pools,
address receiver
) external payable returns (uint256);
function get_dy(address[11] memory route, uint256[5][5] memory swap_params, uint256 amount, address[5] memory pools)
external
view
returns (uint256);
function version() external view returns (string memory);
receive() external payable;
}
"
},
"src/Vault.sol": {
"content": "// SPDX-License-Identifier: LicenseRef-CICADA-Proprietary
// SPDX-FileCopyrightText: (c) 2024 Cicada Software, CICADA DMCC. All rights reserved.
pragma solidity ^0.8.29;
import {SafeERC20} from "@openzeppelin-contracts/token/ERC20/utils/SafeERC20.sol";
import {Address} from "@openzeppelin-contracts/utils/Address.sol";
import {IUniswapV2Router02} from "@uniswap-v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import {AccessControl} from "@openzeppelin-contracts/access/AccessControl.sol";
import {Math} from "@openzeppelin-contracts/utils/math/Math.sol";
import {IERC20} from "@openzeppelin-contracts/token/ERC20/IERC20.sol";
/**
* @title Vault
* @notice Manages funds and executes arbitrage operations on behalf of the DeGate arbitrage engine.
* Handles asset approvals, delegates execution to the strategy, and enforces a USD TVL loss threshold to safeguard funds.
* @dev The Vault interacts with a strategy contract to perform swaps and can be upgraded to integrate new strategies and DeFi protocols.
*/
contract Vault is AccessControl {
using SafeERC20 for IERC20;
using Address for address;
struct VaultReserves {
uint256 baseTokenBalance;
uint256 baseTokenUsdValue;
uint256 quoteTokenBalance;
uint256 quoteTokenUsdValue;
uint256 totalUsdValue;
}
// MANAGER_ROLE: Responsible for managing and upgrading the strategy contract.
// Can grant MANAGER_ROLE and GATEWAY_EXECUTOR_ROLE roles.
// Typically held by the platform staff via a multisignature wallet. This role allows
// for the introduction of new methods and integrations with DeFi protocols.
bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
// GATEWAY_EXECUTOR_ROLE: Held by the arbitrage engine gateway process, this EOA is responsible
// for triggering arbitrage operations and covering the gas costs associated with these transactions.
bytes32 public constant GATEWAY_EXECUTOR_ROLE = keccak256("GATEWAY_EXECUTOR_ROLE");
// FINANCIER_ROLE: Held by the owner of the funds, which could be an externally owned
// account (EOA) or a multisignature wallet. The holder of this role is responsible for
// providing the funding for operations and has the exclusive ability to withdraw funds
// from the vault.
// Can grant FINANCIER_ROLE to other accounts.
bytes32 public constant FINANCIER_ROLE = keccak256("FINANCIER_ROLE");
// MAX_ALLOWED_LOSS_BPS represents the maximum allowed loss in basis points (bps).
// A value of 1000 bps is equivalent to a 10% maximum loss allowed per single action
uint256 public constant MAX_ALLOWED_SINGLE_LOSS_BPS = 100;
uint256 public constant MAX_ALLOWED_CUM_LOSS_BPS = 1000;
address public strategy;
IERC20 public baseToken;
IERC20 public quoteToken;
address[] public reservesEvaluationPath;
address[] public gatewayExecutors;
IUniswapV2Router02 public router;
string public constant version = "v0.1.3-flex";
uint256 public allowedSingleLossBps;
uint256 public allowedCumLossBps;
uint256 public currentCumLossBps;
uint256 public expectedGasBurn;
bool public isFlex;
// These events are emitted during the arbitrage execution process to track the state and results of operations.
// allowing the arbitrage engine to index, fetch, and analyze the outcomes.
// `PreExecState` captures the Vault's initial balances and USD TVL before execution.
// `PostExecState` records the final balances and resulting USD TVL
// `ExecResult` provides the net changes in balances and USD value.
event PreExecState(VaultReserves);
event PostExecState(VaultReserves);
event ExecResult(int256 baseTokenBalanceChange, int256 quoteTokenBalanceChange, int256 totalUsdValueChange);
event AllowedLossUpdated(uint256 allowedSingleLossBps, uint256 allowedCumLossBps);
event StrategyUpdated(address previousStrategy, address newStrategy);
event GatewayExecutorAdded(address executor);
event GatewayExecutorRemoved(address executor);
event ExpectedGasBurnUpdated(uint256 newExpectedGasBurn);
/**
* @dev Initializes the Vault with the provided parameters.
* @param _baseToken Address of the base token (first token in the pair).
* @param _quoteToken Address of the quote token (second token in the pair).
* @param _reservesEvaluationPath Route to the USD stablecoin token (for USD valuation).
* @param _router Address of the Uniswap V2 router (for price impact and USD value calculations).
* @param _allowedSingleLossBps Allowed single-tx loss in 1/10000 basis points (modifiable by FINANCIER_ROLE).
* @param _allowedCumLossBps Allowed cumulative loss loss in 1/10000 basis points (modifiable by FINANCIER_ROLE).
* @param _strategy Address of the strategy contract (modifiable by MANAGER_ROLE).
* @param _financier Address granted the FINANCIER_ROLE (responsible for funding operations).
* @param _gatewayExecutors Addresses granted the GATEWAY_EXECUTOR_ROLE (able to initiate buy/sell operations).
* @param _manager Address granted the MANAGER_ROLE (manages strategy upgrades).
* @param _isFlex Flag to enable/disable flex mode
*/
constructor(
IERC20 _baseToken,
IERC20 _quoteToken,
address[] memory _reservesEvaluationPath,
IUniswapV2Router02 _router,
uint256 _allowedSingleLossBps,
uint256 _allowedCumLossBps,
uint256 _expectedGasBurn,
address _strategy,
address _financier,
address[] memory _gatewayExecutors,
address _manager,
bool _isFlex
) {
isFlex = _isFlex;
_validateTokensAndRouter(address(_baseToken), address(_quoteToken), address(_router));
baseToken = _baseToken;
quoteToken = _quoteToken;
router = _router;
_validateEvaluationPath(_reservesEvaluationPath);
reservesEvaluationPath = _reservesEvaluationPath;
require(_allowedSingleLossBps <= MAX_ALLOWED_SINGLE_LOSS_BPS, "ALLOWED_SINGLE_LOSS_OVER_MAX");
require(_allowedCumLossBps <= MAX_ALLOWED_CUM_LOSS_BPS, "ALLOWED_CUM_LOSS_OVER_MAX");
allowedSingleLossBps = _allowedSingleLossBps;
allowedCumLossBps = _allowedCumLossBps;
strategy = _strategy;
require(_expectedGasBurn > 200_000, "EXPECTED_GAS_BURN_TOO_LOW");
expectedGasBurn = _expectedGasBurn;
_setRoleAdmin(GATEWAY_EXECUTOR_ROLE, MANAGER_ROLE);
_setRoleAdmin(MANAGER_ROLE, MANAGER_ROLE);
_setRoleAdmin(FINANCIER_ROLE, FINANCIER_ROLE);
_grantRole(FINANCIER_ROLE, _financier);
for (uint256 i = 0; i < _gatewayExecutors.length; i++) {
_addGatewayExecutor(_gatewayExecutors[i]);
}
_grantRole(MANAGER_ROLE, _manager);
}
function updateConfig(
IERC20 _baseToken,
IERC20 _quoteToken,
address[] memory _reservesEvaluationPath,
IUniswapV2Router02 _router,
bool _isFlex
) external onlyRole(MANAGER_ROLE) {
_validateTokensAndRouter(address(_baseToken), address(_quoteToken), address(_router));
baseToken = _baseToken;
quoteToken = _quoteToken;
router = _router;
_validateEvaluationPath(_reservesEvaluationPath);
reservesEvaluationPath = _reservesEvaluationPath;
isFlex = _isFlex;
}
receive() external payable {}
/**
* @notice Sets the expected gas burn value.
* @param _expectedGasBurn The new expected gas burn value.
*/
function setExpectedGasBurn(uint256 _expectedGasBurn) external onlyRole(MANAGER_ROLE) {
require(_expectedGasBurn > 200_000, "EXPECTED_GAS_BURN_TOO_LOW");
expectedGasBurn = _expectedGasBurn;
emit ExpectedGasBurnUpdated(_expectedGasBurn);
}
/**
* @notice Updates the allowed USD loss thresholds in basis points (bps).
* @param _allowedSingleLossBps The new allowed single-operation loss in bps (1 bps = 0.01%).
* @param _allowedCumLossBps The new allowed cumulative loss in bps (1 bps = 0.01%).
*
* Example: `setAllowedLoss(100);` sets the allowed loss to 1%.
*/
function setAllowedLoss(uint256 _allowedSingleLossBps, uint256 _allowedCumLossBps)
external
onlyRole(FINANCIER_ROLE)
{
require(_allowedSingleLossBps <= MAX_ALLOWED_SINGLE_LOSS_BPS, "ALLOWED_SINGLE_LOSS_OVER_MAX");
require(_allowedCumLossBps <= MAX_ALLOWED_CUM_LOSS_BPS, "ALLOWED_CUM_LOSS_OVER_MAX");
allowedSingleLossBps = _allowedSingleLossBps;
allowedCumLossBps = _allowedCumLossBps;
currentCumLossBps = 0;
emit AllowedLossUpdated(allowedSingleLossBps, allowedCumLossBps);
}
/**
* @notice Updates the strategy contract used by the Vault.
* @dev This function is used to update the strategy contract that the Vault interacts with for executing arbitrage operations.
* Can only be called by an account with the MANAGER_ROLE (Typically held by the platform staff via a multisignature wallet)
* @param _strategy The address of the new strategy contract.
*/
function setStrategy(address _strategy) external onlyRole(MANAGER_ROLE) {
require(_strategy != address(0), "STRATEGY_NOTSET");
require(_strategy != strategy, "SAME_STRATEGY");
// Revoke approvals from previous strategy for safety
if (strategy != address(0)) {
baseToken.forceApprove(strategy, 0);
quoteToken.forceApprove(strategy, 0);
}
strategy = _strategy;
emit StrategyUpdated(strategy, _strategy);
}
/**
* @dev Adds a new gateway executor.
* @param _executor The address of the executor to add.
*/
function addGatewayExecutor(address _executor) external onlyRole(MANAGER_ROLE) {
_addGatewayExecutor(_executor);
}
/**
* @dev Removes an existing gateway executor.
* @param _executor The address of the executor to remove.
*/
function removeGatewayExecutor(address _executor) external onlyRole(MANAGER_ROLE) {
_removeGatewayExecutor(_executor);
}
/**
* @dev Ensures each gateway executor has at least _minWei wei on its baance.
* @param _minWei The minimum balance units each executor should have.
*/
function replenishExecutorsWei(uint256 _minWei) external onlyRole(MANAGER_ROLE) {
_replenishExecutorsWei(_minWei);
}
/**
* @dev Executes swap operations initiated by an external DeGate process with GATEWAY_EXECUTOR_ROLE.
* Approves and flash-loans specified amounts of base and quote tokens from the Vault to the Strategy contract,
* delegating control for execution. The Strategy completes the operation and returns the funds to the Vault.
* While temporary USD losses due to slippage and DEX fees are expected, the modifier ensures losses
* stay within the allowed threshold, mitigating potential mistakes.
* @param _baseTokenAmount The amount of base tokens to approve and flash-loan to the Strategy.
* @param _quoteTokenAmount The amount of quote tokens to approve and flash-loan to the Strategy.
* @param _params Encoded function selector and parameters for the Strategy contract's execution.
*/
function execute(uint256 _baseTokenAmount, uint256 _quoteTokenAmount, bytes calldata _params)
external
onlyRole(GATEWAY_EXECUTOR_ROLE)
{
baseToken.forceApprove(strategy, _baseTokenAmount);
quoteToken.forceApprove(strategy, _quoteTokenAmount);
VaultReserves memory vaultReservesBefore = getVaultReserves();
emit PreExecState(vaultReservesBefore);
strategy.functionCall(_params);
VaultReserves memory vaultReservesAfter = getVaultReserves();
if (!isFlex) {
_trackAndEnforceLossLimits(vaultReservesBefore, vaultReservesAfter);
}
emit PostExecState(vaultReservesAfter);
emit ExecResult(
int256(vaultReservesAfter.baseTokenBalance) - int256(vaultReservesBefore.baseTokenBalance),
int256(vaultReservesAfter.quoteTokenBalance) - int256(vaultReservesBefore.quoteTokenBalance),
int256(vaultReservesAfter.totalUsdValue) - int256(vaultReservesBefore.totalUsdValue)
);
_replenishExecutorsWei(0);
}
/**
* @notice Withdraws a specified amount of a given token from the Vault.
* @dev Allows the funds' owner to withdraw baseToken, quoteToken, or recover any other tokens (e.g., mistakenly sent) from the Vault.
* This function can only be called by an account with the FINANCIER_ROLE, representing the owner of the funds.
* @param token The ERC20 token to withdraw. If the address is zero, withdraw native token (ETH).
* @param amount The amount of the token to withdraw.
*/
function withdraw(address token, uint256 amount) external onlyRole(FINANCIER_ROLE) {
if (token == address(0)) {
payable(msg.sender).transfer(amount);
} else {
IERC20(token).safeTransfer(msg.sender, amount);
}
}
/**
* @notice Calculates and returns the total USD value of the vault's reserves.
* @dev This function retrieves the balances of two tokens (baseToken and quoteToken),
* converts their respective balances into USD value using a Uniswap-like router,
* and sums the USD values to return the total value of the reserves.
*
* @return usdValue The total USD value of the vault's reserves.
*/
function getVaultReserves() public view returns (VaultReserves memory) {
uint256 baseTokenBalance = baseToken.balanceOf(address(this));
uint256 quoteTokenBalance = quoteToken.balanceOf(address(this));
uint256 baseTokenUsdValue;
uint256 quoteTokenUsdValue;
if (!isFlex) {
// If the route is not explicitly specified, evaluate baseToken by the direct route to quoteToken
// and use theraw quote token balance as USD value
if (reservesEvaluationPath.length == 0) {
address[] memory fullEvaluationPath = new address[](2);
fullEvaluationPath[0] = address(baseToken);
fullEvaluationPath[1] = address(quoteToken);
if (baseTokenBalance > 0) {
fullEvaluationPath[0] = address(baseToken);
baseTokenUsdValue = router.getAmountsOut(baseTokenBalance, fullEvaluationPath)[1];
}
quoteTokenUsdValue = quoteTokenBalance;
} else {
address[] memory fullEvaluationPath = new address[](reservesEvaluationPath.length + 1);
for (uint256 i = 0; i < reservesEvaluationPath.length; i++) {
fullEvaluationPath[i + 1] = reservesEvaluationPath[i];
}
if (baseTokenBalance > 0) {
fullEvaluationPath[0] = address(baseToken);
baseTokenUsdValue = router.getAmountsOut(baseTokenBalance, fullEvaluationPath)[1];
}
if (quoteTokenBalance > 0) {
fullEvaluationPath[0] = address(quoteToken);
quoteTokenUsdValue = router.getAmountsOut(quoteTokenBalance, fullEvaluationPath)[1];
}
}
}
uint256 totalUsdValue = baseTokenUsdValue + quoteTokenUsdValue;
VaultReserves memory reserves = VaultReserves({
baseTokenBalance: baseTokenBalance,
baseTokenUsdValue: baseTokenUsdValue,
quoteTokenBalance: quoteTokenBalance,
quoteTokenUsdValue: quoteTokenUsdValue,
totalUsdValue: totalUsdValue
});
return reserves;
}
/**
* @dev Adds a new gateway executor.
* @param _executor The address of the executor to add.
*/
function _addGatewayExecutor(address _executor) internal {
require(_executor != address(0), "INVALID_EXECUTOR_ADDRESS");
for (uint256 i = 0; i < gatewayExecutors.length; i++) {
require(gatewayExecutors[i] != _executor, "EXECUTOR_ALREADY_EXISTS");
}
_grantRole(GATEWAY_EXECUTOR_ROLE, _executor);
gatewayExecutors.push(_executor);
emit GatewayExecutorAdded(_executor);
}
/**
* @dev Removes an existing gateway executor.
* @param _executor The address of the executor to remove.
*/
function _removeGatewayExecutor(address _executor) internal {
require(_executor != address(0), "INVALID_EXECUTOR_ADDRESS");
_revokeRole(GATEWAY_EXECUTOR_ROLE, _executor);
bool removed = false;
// Remove executor from the array
for (uint256 i = 0; i < gatewayExecutors.length; i++) {
if (gatewayExecutors[i] == _executor) {
gatewayExecutors[i] = gatewayExecutors[gatewayExecutors.length - 1];
gatewayExecutors.pop();
removed = true;
break;
}
}
require(removed, "EXECUTOR_NOT_FOUND");
emit GatewayExecutorRemoved(_executor);
}
/**
* @dev Ensures each gateway executor has at least _minWei.
* @param _minWei The minimum balance each executor should have. If it's 0, it's auto-calculated
*/
function _replenishExecutorsWei(uint256 _minWei) internal {
if (_minWei == 0) {
_minWei = expectedGasBurn * tx.gasprice;
}
for (uint256 i = 0; i < gatewayExecutors.length; i++) {
address executor = gatewayExecutors[i];
uint256 balance = executor.balance;
if (balance < _minWei) {
uint256 amountToSend = _minWei - balance;
if (address(this).balance < amountToSend) {
// Exit the loop and function if the vault's balance is not enough
break;
}
payable(executor).transfer(amountToSend);
}
}
}
/**
* @dev Tracks and enforces loss limits based on the change in reserves.
* This function calculates the loss in USD value between the reserves before and after an operation.
* It then converts this loss to basis points (bps) and ensures that the loss does not exceed the allowed single loss
* and cumulative loss limits. If the loss exceeds these limits, the function reverts.
*
* @param reservesBefore The reserves before the operation.
* @param reservesAfter The reserves after the operation.
*/
function _trackAndEnforceLossLimits(VaultReserves memory reservesBefore, VaultReserves memory reservesAfter)
internal
{
if (isFlex) return;
if (reservesBefore.totalUsdValue > reservesAfter.totalUsdValue) {
uint256 singleLossUsd = reservesBefore.totalUsdValue - reservesAfter.totalUsdValue;
// Ensure singleLossBps is at least 1 if a loss occurred to prevent exploiting rounding errors
uint256 singleLossBps = Math.max((singleLossUsd * 10000) / reservesBefore.totalUsdValue, 1);
currentCumLossBps += singleLossBps;
require(singleLossBps <= allowedSingleLossBps, "SINGLE_LOSS_EXCEEDS_ALLOWED");
require(currentCumLossBps <= allowedCumLossBps, "CUM_LOSS_EXCEEDS_ALLOWED");
}
}
function _validateTokensAndRouter(address _baseToken, address _quoteToken, address _router) internal pure {
require(_baseToken != address(0), "BASE_TOKEN_NOT_SET");
require(_quoteToken != address(0), "QUOTE_TOKEN_NOT_SET");
require(_router != address(0), "ROUTER_NOT_SET");
require(_baseToken != _quoteToken, "BASE_AND_QUOTE_EQUAL");
}
function _validateEvaluationPath(address[] memory _reservesEvaluationPath) internal view {
if (isFlex) return;
for (uint256 i = 0; i < _reservesEvaluationPath.length; i++) {
require(_reservesEvaluationPath[i] != address(0), "EVALUATION_PATH_CONTAINS_ZERO");
require(_reservesEvaluationPath[i] != address(baseToken), "EVALUATION_PATH_CONTAINS_BASE");
require(_reservesEvaluationPath[i] != address(quoteToken), "EVALUATION_PATH_CONTAINS_QUOTE");
}
}
}
"
},
"src/lib/Common.sol": {
"content": "// SPDX-License-Identifier: LicenseRef-CICADA-Proprietary
// SPDX-FileCopyrightText: (c) 2024 Cicada Software, CICADA DMCC. All rights reserved.
pragma solidity ^0.8.29;
enum Exact {
In,
Out
}
library Enums {
enum Direction {
QuoteToBase,
BaseToQuote
}
enum Flavor {
UniV2Legacy,
UniV3QuoterV2,
BalancerV2,
Curve
}
}
"
},
"src/mux/CurveQuoter.sol": {
"content": "// SPDX-License-Identifier: LicenseRef-CICADA-Proprietary
// SPDX-FileCopyrightText: (c) 2024 Cicada Software, CICADA DMCC. All rights reserved.
pragma solidity ^0.8.28;
/* ====== INTERFACES IMPORTS ====== */
import {ICurveQuoter, SwapParams, SwapType, PoolType} from "../interfaces/ICurveQuoter.sol";
import {ICurveRouter} from "../interfaces/curve/IRouter.sol";
import {IPoolCommon} from "../interfaces/curve/pools/IPoolCommon.sol";
import {IStableSwapPool} from "../interfaces/curve/pools/IStableSwapPool.sol";
/* ====== CONTRACTS IMPORTS ====== */
import {Vault} from "../Vault.sol";
import {Enums, Exact} from "../lib/Common.sol";
/**
* @title CurveStrategy
* @notice This contract is a router for Curve, that creates unified interface
* for Vault contracts to interact with Curve protocol
*/
abstract contract CurveQuoter is ICurveQuoter {
/* ======== STATE ======== */
/// @inheritdoc ICurveQuoter
address public immutable ROUTER;
/* ======== ERRORS ======== */
/// @notice Revert for tokenIn is not quote token for BUY direction
error TokenInIsNotQuoteTokenForBuyDirection();
/// @notice Revert for tokenIn is not base token for SELL direction
error TokenInIsNotBaseTokenForSellDirection();
/// @notice Revert for tokenOut is not quote token for SELL direction
error TokenOutIsNotQuoteTokenForSellDirection();
/// @notice Revert for tokenOut is not base token for BUY direction
error TokenOutIsNotBaseTokenForBuyDirection();
/// @notice Revert for interrupted path, f.e. token out of some hop is not token in for next hop
error InterruptedPath();
/// @notice Revert for 0 amounts
error ZeroAmount();
/// @notice CurveRouterNG doesn't support more than 5 pools in the route
error InvalidSwapParamsLength();
/* ======== CONSTRUCTOR AND INIT ======== */
/**
* @notice Initializes the Strategy with the provided Curve Router.
* @param _router Address of the Curve Router NG.
*/
constructor(address _router) {
require(_router != address(0), "CurveStrategy: ZERO_ROUTER");
ROUTER = _router;
}
/* ======== EXTERNAL/PUBLIC ======== */
/// @inheritdoc ICurveQuoter
function quote(Exact exactType, uint256 amount, SwapParams[] memory swapParams)
public
view
returns (uint256 amountIn, uint256 amountOut)
{
if (amount == 0) revert ZeroAmount();
if (swapParams.length == 0 || swapParams.length > 5) revert InvalidSwapParamsLength();
(address[11] memory route, address[5] memory pools) = _buildRoute(swapParams);
uint256[5][5] memory _swapParams = _buildSwapParams(swapParams);
ICurveRouter router = ICurveRouter(payable(ROUTER));
if (exactType == Exact.Out) {
uint256 amountToSwap = amount;
// Iterate through pools in reverse order
for (uint256 i = swapParams.length; i > 0; i--) {
if (swapParams[i - 1].poolType == PoolType.Stable) {
int128 inIndex = int128(int8(swapParams[i - 1].tokenInIndex));
int128 outIndex = int128(int8(swapParams[i - 1].tokenOutIndex));
amountToSwap = IStableSwapPool(pools[i - 1]).get_dx(inIndex, outIndex, amountToSwap);
} else {
uint256 inIndex = uint256(swapParams[i - 1].tokenInIndex);
uint256 outIndex = uint256(swapParams[i - 1].tokenOutIndex);
amountToSwap = IPoolCommon(pools[i - 1]).get_dx(inIndex, outIndex, amountToSwap);
}
}
amountIn = amountToSwap;
amountOut = amount;
} else {
amountOut = router.get_dy(route, _swapParams, amount, pools);
amountIn = amount;
}
}
/**
* @notice Builds the route for the swap
* @param swapParams the array of swap parameters
* @return route array that consists of [token0, pool0, token1, pool1, token2, ...] sequences
* @return pools array of pool addresses
*/
function _buildRoute(SwapParams[] memory swapParams)
internal
view
returns (address[11] memory route, address[5] memory pools)
{
if (swapParams.length == 0 || swapParams.length > 5) revert InvalidSwapParamsLength();
for (uint256 i = 0; i < swapParams.length; i++) {
address pool = swapParams[i].pool;
address tokenIn = IPoolCommon(pool).coins(swapParams[i].tokenInIndex);
route[i * 2] = tokenIn;
route[i * 2 + 1] = pool;
if (i == swapParams.length - 1) {
address tokenOut = IPoolCommon(pool).coins(swapParams[i].tokenOutIndex);
route[i * 2 + 2] = tokenOut;
}
}
for (uint256 i = 0; i < swapParams.length; i++) {
pools[i] = swapParams[i].pool;
}
return (route, pools);
}
/**
* @notice Builds the swap params for exchange() function of CurveRouterNG
* @dev adds swapType to parameters
* @param swapParams the array of swap parameters
* @return _swapParams array of swap params
* @dev Line structure:
* [i, j, swap_type, PoolType poolType, n_coins]
* i - index of the input token
* j - index of the output token
* n_coins - number of coins in the pool
*/
function _buildSwapParams(SwapParams[] memory swapParams)
internal
pure
returns (uint256[5][5] memory _swapParams)
{
uint256 swapType = uint256(SwapType.Standard);
for (uint256 i = 0; i < swapParams.length; i++) {
_swapParams[i] = [
swapParams[i].tokenInIndex,
swapParams[i].tokenOutIndex,
swapType,
uint8(swapParams[i].poolType),
swapParams[i].coinsInPool
];
}
}
/**
* @notice Validates the route for the swap
* @param swapParams the array of swap parameters
* @param direction the direction of the swap
* @param vault the address of the vault
*/
function _validateSwapParams(SwapParams[] memory swapParams, Enums.Direction direction, address vault)
internal
view
{
address baseToken = address(Vault(payable(vault)).baseToken());
address quoteToken = address(Vault(payable(vault)).quoteToken());
address tokenIn = IPoolCommon(swapParams[0].pool).coins(swapParams[0].tokenInIndex);
SwapParams memory lastHop = swapParams[swapParams.length - 1];
address tokenOut = IPoolCommon(lastHop.pool).coins(lastHop.tokenOutIndex);
for (uint256 i = 0; i < swapParams.length - 1; i++) {
address tokenOutPrevHop = IPoolCommon(swapParams[i].pool).coins(swapParams[i].tokenOutIndex);
address tokenInNextHop = IPoolCommon(swapParams[i + 1].pool).coins(swapParams[i + 1].tokenInIndex);
if (tokenOutPrevHop != tokenInNextHop) {
revert InterruptedPath();
}
}
if (_isBuy(direction)) {
if (tokenIn != quoteToken) revert TokenInIsNotQuoteTokenForBuyDirection();
if (tokenOut != baseToken) revert TokenOutIsNotBaseTokenForBuyDirection();
} else {
if (tokenIn != baseToken) revert TokenInIsNotBaseTokenForSellDirection();
if (tokenOut != quoteToken) revert TokenOutIsNotQuoteTokenForSellDirection();
}
}
/// @notice Checks if the direction is a buy
/// @param direction the direction of the swap
/// @return true if the direction is a buy, false otherwise
function _isBuy(Enums.Direction direction) internal pure virtual returns (bool) {
return direction == Enums.Direction.QuoteToBase;
}
}
"
},
"dependencies/@openzeppelin-contracts-5.2.0/interfaces/IERC1363.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
"
},
"dependencies/@openzeppelin-contracts-5.2.0/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
"
},
"dependencies/@openzeppelin-contracts-5.2.0/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined b
Submitted on: 2025-09-24 20:46:02
Comments
Log in to comment.
No comments yet.