Verified contractExactBUSL-1.1
CurveFiEvaluator
Address0x1e51b2c87cf6ee02c69ad46f333ddee3d1a5da7d
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.22
- Same code
1 more contract
Details
- Compiler
- solc 0.8.22+commit.4fc1097e
- Language
- solidity
- Optimization
- Yes, 1,000,000 runs
- EVM version
- paris
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,391,856
- Creation transaction
- 0x1a3ebc21a8…d3a3d23474
35 files
- contracts/compiler/curveFi/CurveFiEvaluator.solmain2.12 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol8.91 KB
- @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol1.18 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/utils/Address.sol6.26 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol869 B
- contracts/compiler/base/LiquidityPoolsRepository.sol2.38 KB
- contracts/compiler/curveFi/CurveFiLiquidityPoolsRepository.sol7.29 KB
- contracts/compiler/curveFi/actions/CurveFiDecreasePosition.sol4.62 KB
- contracts/compiler/curveFi/actions/CurveFiExchange.sol3.18 KB
- contracts/compiler/curveFi/libraries/CurveFiLib.sol1.44 KB
- contracts/compiler/libraries/Path.sol2.15 KB
- contracts/interfaces/base/CommonErrors.sol1.21 KB
- contracts/interfaces/base/IERC165Extended.sol1.18 KB
- contracts/interfaces/compiler/Command.sol606 B
- contracts/interfaces/compiler/adapters/IDecreasePositionEvaluator.sol1.44 KB
- contracts/interfaces/compiler/adapters/IExchangeEvaluator.sol1.51 KB
- contracts/interfaces/compiler/adapters/IIncreasePositionEvaluator.sol1.46 KB
- contracts/interfaces/compiler/adapters/ILiquidityPoolsRepository.sol2.49 KB
- contracts/interfaces/compiler/adapters/PositionDescriptor.sol503 B
- contracts/interfaces/compiler/adapters/index.sol739 B
- contracts/interfaces/compliance/Asset.sol407 B
- contracts/interfaces/compliance/IWhitelistingController.sol11.3 KB
- contracts/interfaces/compliance/IWhitelistingControllerAgreement.sol4.37 KB
- contracts/interfaces/compliance/internal/curveFi/ICurveFiGauge.sol803 B
- contracts/interfaces/compliance/internal/curveFi/ICurveFiMinter.sol256 B
- contracts/interfaces/compliance/internal/curveFi/ICurveFiPool.sol10.64 KB
- contracts/interfaces/compliance/internal/curveFi/ICurveFiRouter.sol537 B
- contracts/interfaces/compliance/internal/curveFi/ICurveFiZapper.sol3.88 KB
- contracts/interfaces/compliance/internal/curveFi/index.sol321 B
- contracts/libraries/Address.sol1.18 KB
- contracts/libraries/AssetLibrary.sol1.57 KB
- contracts/libraries/CommandLibrary.sol2.6 KB
- contracts/libraries/SafeCall.sol1.24 KB
- solady/src/utils/SafeTransferLib.sol16.43 KB
contracts/compiler/curveFi/CurveFiEvaluator.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {
IDecreasePositionEvaluator,
IExchangeEvaluator
} from "contracts/interfaces/compiler/adapters/index.sol";
import {Command} from "contracts/interfaces/compiler/Command.sol";
import {Path} from "../libraries/Path.sol";
import {CurveFiDecreasePosition} from "./actions/CurveFiDecreasePosition.sol";
import {CurveFiExchange} from "./actions/CurveFiExchange.sol";
import {CurveFiLiquidityPoolsRepository} from "./CurveFiLiquidityPoolsRepository.sol";
contract CurveFiEvaluator is
IDecreasePositionEvaluator,
IExchangeEvaluator,
CurveFiLiquidityPoolsRepository,
CurveFiExchange,
CurveFiDecreasePosition
{
using Address for address;
using Path for bytes;
error CurveFiV1CantExchangeToDifferentAddress();
function evaluate(
address operator,
ExchangeRequest calldata request
) external view override returns (Command[] memory cmds) {
// TODO: we can specify recipient for V2 pools, but currently this feature is not needed
if (operator != request.recipient) revert CurveFiV1CantExchangeToDifferentAddress();
(address tokenIn, address target, uint256 value, bytes memory data) = constructExchange(
request.path,
request.amountIn,
request.minAmountOut
);
Command memory cmd = Command({target: target, value: value, payload: data});
cmds = value == 0 ? cmd.populateWithApprove(tokenIn, request.amountIn) : cmd.asArray();
}
function evaluate(
address,
DecreasePositionRequest calldata request
) external view override returns (Command[] memory cmds) {
(
bool needApprove,
address lpToken,
address target,
bytes memory data
) = constructDecreasePosition(request);
Command memory cmd = Command({target: target, value: 0, payload: data});
cmds = needApprove ? cmd.populateWithApprove(lpToken, request.liquidity) : cmd.asArray();
}
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 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 ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* 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.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) 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 FailedInnerCall();
}
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
contracts/compiler/base/LiquidityPoolsRepository.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {
AlreadyUpToDate,
ILiquidityPoolsRepository,
PoolIdNotFound,
PoolIsNotSupported,
Status
} from "contracts/interfaces/compiler/adapters/index.sol";
abstract contract LiquidityPoolsRepository is ILiquidityPoolsRepository {
modifier getPoolGuard(uint256 _poolId) {
Status status = getPoolStatus(_poolId);
if (status == Status.Undefined) revert PoolIsNotSupported(_poolId);
_;
}
// Interface implementation
function updatePoolSupport(
bytes calldata _encodedParams,
bool _supported
) external override returns (uint256 poolId_) {
poolId_ = getPoolIdFromParams(_encodedParams);
Status status = getPoolStatus(poolId_);
if (_supported && status == Status.Undefined) {
return initializePool(_encodedParams);
}
if (_supported && status == Status.Suspended) {
setPoolStatus(poolId_, Status.Supported);
return poolId_;
}
if (!_supported && status == Status.Supported) {
setPoolStatus(poolId_, Status.Suspended);
return poolId_;
}
if (
_supported && status == Status.Supported && refreshPoolConfig(poolId_, _encodedParams)
) {
return poolId_;
}
revert AlreadyUpToDate();
}
function getPoolId(
bytes calldata _encodedTokens
) external view override returns (uint256 poolId_) {
if (getPoolStatus(poolId_ = getPoolIdFromTokens(_encodedTokens)) == Status.Undefined) {
revert PoolIdNotFound(_encodedTokens);
}
}
function getPoolStatus(uint256 _poolId) public view virtual override returns (Status);
// Internal fixture
function initializePool(
bytes calldata _encodedParams
) internal virtual returns (uint256 poolId_);
function setPoolStatus(uint256 _poolId, Status _status) internal virtual;
function refreshPoolConfig(uint256, bytes calldata) internal virtual returns (bool) {
return false;
}
function getPoolIdFromParams(
bytes calldata _encodedParams
) internal view virtual returns (uint256 poolId_);
function getPoolIdFromTokens(
bytes calldata _encodedTokens
) internal view virtual returns (uint256 poolId_);
}
contracts/compiler/curveFi/CurveFiLiquidityPoolsRepository.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {
ICurveFiGauge,
ICurveFiPool,
ICurveFiZapper
} from "contracts/interfaces/compliance/internal/curveFi/index.sol";
import {Address} from "contracts/libraries/Address.sol";
import {LiquidityPoolsRepository, Status} from "../base/LiquidityPoolsRepository.sol";
import {CurveFiLib} from "./libraries/CurveFiLib.sol";
/// @dev Selects the `remove_liquidity` ABI a pool exposes. `Legacy` is the fixed-array form
/// used by classic pools. `StableSwapNG` uses the dynamic-array overload. Legacy is intentionally
/// value 0 so that every pool registered before this field existed reads back as Legacy.
/// @dev Only StableSwap-NG switched remove_liquidity to a dynamic array so it is the sole
/// non-legacy form modeled here. Curve crypto pools (including twocrypto-ng / tricrypto-ng) keep
/// fixed-size arrays (uint256[2] / uint256[3]) and are already handled by the Legacy path.
enum CurvePoolType {
Legacy,
StableSwapNG
}
/// @dev `poolType` is appended at the end of the struct: existing stored pools were written when
/// the field did not exist so its slot byte is zero and reads back as `Legacy`.
/// Never reorder or insert fields before it.
struct CurveFiPool {
ICurveFiPool ref;
uint80 basePoolId;
uint8 nCoins;
bool use256;
ICurveFiZapper zapper;
ICurveFiGauge gauge;
Status status;
CurvePoolType poolType;
}
abstract contract CurveFiLiquidityPoolsRepository is LiquidityPoolsRepository {
using CurveFiLib for ICurveFiPool;
struct Storage {
uint256 currentPoolId;
mapping(bytes32 poolTokensHash => uint256 poolId) ids;
mapping(uint256 poolId => CurveFiPool) pools;
}
// keccak256("CurveFi Liquidity Pools State V1")
bytes32 internal constant STORAGE_SLOT =
0x58ebf467944ec58ecf545c6ac01f80ed366183078a791b197feed2e14cc85f3b;
error NCoinsParamMismatch(uint8 provided, uint256 actual);
error StableSwapNGMetapoolNotSupported();
function getPoolStatus(uint256 poolId) public view override returns (Status) {
return _storage().pools[poolId].status;
}
/// @dev `encodedParams` is `(address deposit, uint80 basePoolId, uint8 nCoins, address zapper,
/// address gauge)` with an optional trailing `uint8 poolType`. The 5-field form (every existing
/// registration encoder) registers a Legacy pool. Append `uint8(CurvePoolType.StableSwapNG)` to
/// register an NG pool.
function initializePool(
bytes calldata encodedParams
) internal override returns (uint256 poolId_) {
(address deposit, uint80 basePoolId, uint8 nCoinsParam, address zapper, address gauge) = abi
.decode(encodedParams, (address, uint80, uint8, address, address));
(, CurvePoolType poolType) = _readPoolType(encodedParams);
if (basePoolId != 0) _requireLegacyMetapool(poolType, getPool(basePoolId).poolType);
ICurveFiPool pool = ICurveFiPool(deposit);
(address[4] memory tokens, uint256 nCoins) = pool.getTokens();
if (nCoinsParam != nCoins) revert NCoinsParamMismatch(nCoinsParam, nCoins);
// Determine whether the pool is V2 (uint256 index) or V1 (int128 index)
bool use256;
try pool.mid_fee() returns (uint256) {
use256 = true;
} catch {
use256 = false;
}
Storage storage $ = _storage();
$.ids[hash(tokens)] = ++$.currentPoolId;
$.pools[poolId_ = $.currentPoolId] = CurveFiPool({
ref: pool,
basePoolId: basePoolId,
nCoins: uint8(nCoins),
use256: use256,
zapper: ICurveFiZapper(zapper),
gauge: ICurveFiGauge(gauge),
status: Status.Supported,
poolType: poolType
});
}
function setPoolStatus(uint256 poolId, Status status) internal override {
_storage().pools[poolId].status = status;
}
/// @dev Migration hook: re-submitting a supported pool with the 6-field encoding updates its
/// `poolType` in place. A 5-field encoding carries no type so it leaves the pool untouched
/// and cannot silently downgrade an NG pool back to Legacy.
/// @dev Only fires while the pool is Supported: a Suspended pool's re-submit is consumed by the
/// earlier resume branch (flips it to Supported without touching poolType) so migrating a
/// suspended pool is a two-step: resume it then re-submit again to set the type.
function refreshPoolConfig(
uint256 poolId,
bytes calldata encodedParams
) internal override returns (bool) {
(bool present, CurvePoolType poolType) = _readPoolType(encodedParams);
if (!present) return false;
CurveFiPool storage pool = _storage().pools[poolId];
if (pool.poolType == poolType) return false;
if (pool.basePoolId != 0) _requireLegacyMetapool(poolType, CurvePoolType.Legacy);
pool.poolType = poolType;
return true;
}
function getPool(
uint256 poolId
) internal view getPoolGuard(poolId) returns (CurveFiPool storage) {
return _storage().pools[poolId];
}
function getPoolIdFromParams(
bytes calldata encodedParams
) internal view override returns (uint256 poolId) {
(address deposit, , , , ) = abi.decode(
encodedParams,
(address, uint80, uint8, address, address)
);
(address[4] memory tokens, ) = ICurveFiPool(deposit).getTokens();
return _storage().ids[hash(tokens)];
}
function getPoolIdFromTokens(
bytes calldata encodedTokens
) internal view override returns (uint256 poolId) {
address[] memory tokens = abi.decode(encodedTokens, (address[]));
address[4] memory tokensFixed;
if (tokens.length == 2) tokensFixed = [tokens[0], tokens[1], address(0), address(0)];
else if (tokens.length == 3) tokensFixed = [tokens[0], tokens[1], tokens[2], address(0)];
else if (tokens.length == 4) tokensFixed = [tokens[0], tokens[1], tokens[2], tokens[3]];
else return 0;
return _storage().ids[hash(tokensFixed)];
}
/// @dev https://github.com/cantinasec/arkis-060902/issues/52
/// @dev We don't support the newer MetaZapNG, which by nature means we must exclude NG Metapool and NG Basepools for dynamic-sized pool token array
function _requireLegacyMetapool(
CurvePoolType poolType,
CurvePoolType basePoolType
) internal pure {
if (poolType != CurvePoolType.Legacy || basePoolType != CurvePoolType.Legacy)
revert StableSwapNGMetapoolNotSupported();
}
function _storage() private pure returns (Storage storage $) {
assembly {
$.slot := STORAGE_SLOT
}
}
function hash(address[4] memory tokens) private pure returns (bytes32) {
return keccak256(abi.encodePacked(Address.sort(tokens)));
}
function _readPoolType(
bytes calldata encodedParams
) private pure returns (bool present, CurvePoolType poolType) {
if (encodedParams.length < 6 * 32) return (false, CurvePoolType.Legacy);
return (true, CurvePoolType(abi.decode(encodedParams[5 * 32:], (uint8))));
}
}
contracts/compiler/curveFi/actions/CurveFiDecreasePosition.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {MinAmountOutMustNotBeZero} from "contracts/interfaces/base/CommonErrors.sol";
import {IDecreasePositionEvaluator} from "contracts/interfaces/compiler/adapters/index.sol";
import {
CurveFiLiquidityPoolsRepository,
CurveFiPool,
CurvePoolType
} from "../CurveFiLiquidityPoolsRepository.sol";
abstract contract CurveFiDecreasePosition is CurveFiLiquidityPoolsRepository {
bytes4 private constant REMOVE_LIQUIDITY_2 =
bytes4(keccak256("remove_liquidity(uint256,uint256[2])"));
bytes4 private constant REMOVE_LIQUIDITY_3 =
bytes4(keccak256("remove_liquidity(uint256,uint256[3])"));
bytes4 private constant REMOVE_LIQUIDITY_4 =
bytes4(keccak256("remove_liquidity(uint256,uint256[4])"));
bytes4 private constant REMOVE_LIQUIDITY_ZAPPER =
bytes4(keccak256("remove_liquidity(address,uint256,uint256[4])"));
bytes4 private constant REMOVE_LIQUIDITY_NG =
bytes4(keccak256("remove_liquidity(uint256,uint256[])"));
error InvalidMinOutputLength(uint256 provided, uint256 configured);
function constructDecreasePosition(
IDecreasePositionEvaluator.DecreasePositionRequest calldata request
) internal view returns (bool needApprove, address lpToken, address target, bytes memory data) {
uint256 length = request.minOutput.length;
uint256 i;
while (i < length) {
if (request.minOutput[i].amount == 0) revert MinAmountOutMustNotBeZero();
unchecked {
++i;
}
}
CurveFiPool storage pool = getPool(request.descriptor.poolId);
if (length != pool.nCoins)
revert InvalidMinOutputLength(request.minOutput.length, pool.nCoins);
uint256 basePoolId = pool.basePoolId;
if (basePoolId == 0) {
target = address(pool.ref);
data = pool.poolType == CurvePoolType.StableSwapNG
? _constructNG(pool.nCoins, request)
: _construct(pool.nCoins, request);
} else {
CurveFiPool storage basePool = getPool(basePoolId);
_requireLegacyMetapool(pool.poolType, basePool.poolType);
needApprove = true;
target = address(basePool.zapper);
lpToken = address(pool.gauge.lp_token());
data = _constructZapper(address(pool.ref), request);
}
}
function _constructZapper(
address target,
IDecreasePositionEvaluator.DecreasePositionRequest calldata request
) private pure returns (bytes memory payload) {
uint256[4] memory minOutput;
uint256 i;
while (i < request.minOutput.length) {
minOutput[i] = request.minOutput[i].amount;
unchecked {
++i;
}
}
payload = abi.encodeWithSelector(
REMOVE_LIQUIDITY_ZAPPER,
target,
request.liquidity,
minOutput
);
}
function _constructNG(
uint256 nCoins,
IDecreasePositionEvaluator.DecreasePositionRequest calldata request
) private pure returns (bytes memory payload) {
uint256[] memory minOutput = new uint256[](nCoins);
for (uint256 i = 0; i < nCoins; ++i) {
minOutput[i] = request.minOutput[i].amount;
}
payload = abi.encodeWithSelector(REMOVE_LIQUIDITY_NG, request.liquidity, minOutput);
}
function _construct(
uint256 nCoins,
IDecreasePositionEvaluator.DecreasePositionRequest calldata request
) private pure returns (bytes memory payload) {
if (nCoins == 2) {
payload = abi.encodeWithSelector(
REMOVE_LIQUIDITY_2,
request.liquidity,
[request.minOutput[0].amount, request.minOutput[1].amount]
);
} else if (nCoins == 3) {
payload = abi.encodeWithSelector(
REMOVE_LIQUIDITY_3,
request.liquidity,
[
request.minOutput[0].amount,
request.minOutput[1].amount,
request.minOutput[2].amount
]
);
} else {
payload = abi.encodeWithSelector(
REMOVE_LIQUIDITY_4,
request.liquidity,
[
request.minOutput[0].amount,
request.minOutput[1].amount,
request.minOutput[2].amount,
request.minOutput[3].amount
]
);
}
}
}
contracts/compiler/curveFi/actions/CurveFiExchange.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Path} from "contracts/compiler/libraries/Path.sol";
import {Address} from "contracts/libraries/Address.sol";
import {
CurveFiLiquidityPoolsRepository,
CurveFiPool,
ICurveFiPool
} from "../CurveFiLiquidityPoolsRepository.sol";
import {CurveFiLib} from "../libraries/CurveFiLib.sol";
abstract contract CurveFiExchange is CurveFiLiquidityPoolsRepository {
using CurveFiLib for ICurveFiPool;
using Address for address;
using Path for bytes;
bytes4 private constant SELECTOR_EXCHANGE_256_ETH =
bytes4(keccak256("exchange(uint256,uint256,uint256,uint256,bool)"));
bytes4 private constant SELECTOR_EXCHANGE_256 =
bytes4(keccak256("exchange(uint256,uint256,uint256,uint256)"));
bytes4 private constant SELECTOR_EXCHANGE_128 =
bytes4(keccak256("exchange(int128,int128,uint256,uint256)"));
bytes4 private constant SELECTOR_EXCHANGE_UNDERLYING_256 =
bytes4(keccak256("exchange_underlying(uint256,uint256,uint256,uint256)"));
bytes4 private constant SELECTOR_EXCHANGE_UNDERLYING_128 =
bytes4(keccak256("exchange_underlying(int128,int128,uint256,uint256)"));
/* solhint-disable func-param-name-mixedcase, var-name-mixedcase */
function constructExchange(
bytes calldata path,
uint256 dx,
uint256 min_dy
) internal view returns (address tokenIn, address target, uint256 value, bytes memory data) {
address tokenOut;
uint256 poolId;
(tokenIn, tokenOut, poolId) = path.extractPool(0);
CurveFiPool storage pool = getPool(poolId);
CurveFiPool storage basePool = pool.basePoolId != 0 ? getPool(pool.basePoolId) : pool;
uint256 i = pool.ref.getTokenIndex(pool.nCoins, basePool.ref, basePool.nCoins, tokenIn);
uint256 j = pool.ref.getTokenIndex(pool.nCoins, basePool.ref, basePool.nCoins, tokenOut);
target = address(pool.ref);
if (tokenIn.isEth()) value = dx;
data = pool.basePoolId == 0
? constructExchange(pool.use256, i, j, dx, min_dy, value != 0)
: constructExchangeUnderlying(pool.use256, i, j, dx, min_dy);
}
function constructExchange(
bool use256,
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy,
bool useEth
) private pure returns (bytes memory data) {
bytes4 selector = use256
? (useEth ? SELECTOR_EXCHANGE_256_ETH : SELECTOR_EXCHANGE_256)
: SELECTOR_EXCHANGE_128;
data = useEth
? abi.encodeWithSelector(selector, i, j, dx, min_dy, true)
: abi.encodeWithSelector(selector, i, j, dx, min_dy);
}
function constructExchangeUnderlying(
bool use256,
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy
) private pure returns (bytes memory data) {
bytes4 selector = use256
? SELECTOR_EXCHANGE_UNDERLYING_256
: SELECTOR_EXCHANGE_UNDERLYING_128;
data = abi.encodeWithSelector(selector, i, j, dx, min_dy);
}
/* solhint-disable func-param-name-mixedcase, var-name-mixedcase */
}
contracts/compiler/curveFi/libraries/CurveFiLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {ICurveFiPool} from "contracts/interfaces/compliance/internal/curveFi/index.sol";
library CurveFiLib {
error TokenIndexNotFoundInCurveFiPool(address token, address pool);
function getTokens(
ICurveFiPool pool
) internal view returns (address[4] memory tokens, uint256 nCoins) {
while (nCoins < 4) {
try pool.coins(nCoins) returns (address token) {
tokens[nCoins] = token;
unchecked {
++nCoins;
}
} catch {
break;
}
}
}
function getTokenIndex(
ICurveFiPool pool,
uint256 nCoinsPool,
ICurveFiPool basePool,
uint256 nCoinsBasePool,
address token
) internal view returns (uint256 index) {
index = pool == basePool ? _getTokenIndex(pool, nCoinsPool, token) : pool.coins(0) == token
? 0
: _getTokenIndex(basePool, nCoinsBasePool, token) + 1;
}
function _getTokenIndex(
ICurveFiPool pool,
uint256 nCoins,
address token
) private view returns (uint256 index) {
while (index < nCoins) {
if (pool.coins(index) == token) return index;
unchecked {
++index;
}
}
revert TokenIndexNotFoundInCurveFiPool(token, address(pool));
}
}
contracts/compiler/libraries/Path.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
library Path {
using Path for bytes;
uint256 internal constant ADDRESS_LEN = 20;
uint256 internal constant POOL_ID_LEN = 4;
uint256 internal constant NEXT_OFFSET = ADDRESS_LEN + POOL_ID_LEN;
error InvalidPathLength(uint256);
function extractTokenIn(bytes calldata _path) internal pure returns (address tokenIn_) {
_path.ensureValid();
tokenIn_ = _path.extractTokenInUnsafe();
}
function extractTokenInUnsafe(bytes calldata _path) internal pure returns (address tokenIn_) {
tokenIn_ = address(bytes20(_path[0:ADDRESS_LEN]));
}
function extractTokenOut(bytes calldata _path) internal pure returns (address tokenOut_) {
_path.ensureValid();
tokenOut_ = _path.extractTokenOutUnsafe();
}
function extractTokenOutUnsafe(bytes calldata _path) internal pure returns (address tokenOut_) {
uint256 len = _path.length;
tokenOut_ = address(bytes20(_path[len - ADDRESS_LEN:len]));
}
/* solhint-disable var-name-mixedcase */
function extractPool(
bytes calldata _path,
uint256 _poolNumber
) internal pure returns (address tokenIn__, address tokenOut_, uint32 poolId_____) {
/* solhint-enable var-name-mixedcase */
_path.ensureValid();
uint256 ptr = _poolNumber * NEXT_OFFSET;
tokenIn__ = address(bytes20(_path[ptr:(ptr = ptr + ADDRESS_LEN)]));
poolId_____ = uint32(bytes4(_path[ptr:(ptr = ptr + POOL_ID_LEN)]));
tokenOut_ = address(bytes20(_path[ptr:(ptr = ptr + ADDRESS_LEN)]));
}
function getNumberOfPools(bytes calldata _path) internal pure returns (uint256) {
_path.ensureValid();
return (_path.length - ADDRESS_LEN) / NEXT_OFFSET;
}
function ensureValid(bytes calldata _path) internal pure {
if (!isValid(_path)) revert InvalidPathLength(_path.length);
}
function isValid(bytes calldata _path) private pure returns (bool) {
if (_path.length < ADDRESS_LEN) return false;
return (_path.length - ADDRESS_LEN) % NEXT_OFFSET == 0;
}
}
contracts/interfaces/base/CommonErrors.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
/**
* @notice An error indicating that the amount for the specified token is zero.
* @param token The address of the token with a zero amount.
*/
error AmountMustNotBeZero(address token);
/**
* @notice An error indicating that an address must not be zero.
*/
error AddressMustNotBeZero();
/**
* @notice An error indicating that an array must not be empty.
*/
error ArrayMustNotBeEmpty();
/**
* @notice An error indicating that an string must not be empty.
*/
error StringMustNotBeEmpty();
/**
* @notice An error indicating storage is already up to date and doesn't need further processing.
* @dev This error is thrown when attempting to update an entity(s) that is(are) already up to date.
*/
error AlreadyUpToDate();
/**
* @notice An error indicating that an action is unauthorized for the specified account.
* @param account The address of the unauthorized account.
*/
error UnauthorizedAccount(address account);
/**
* @notice An error indicating that the min amount out must not be zero.
*/
error MinAmountOutMustNotBeZero();
/**
* @notice An error indicating that the threshold exceeds the maximum allowed value.
*/
contracts/interfaces/base/IERC165Extended.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
/* solhint-disable no-unused-import */
import {
IERC165
} from "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
/* solhint-enable no-unused-import */
/**
* @notice An error indicating that an address does not support the expected interface
* @param implementation The address that does not implement the required interface
*/
error UnsupportedInterface(address implementation);
/**
* @dev Extended interface of the ERC165 standard to ensure compatibility
* with Diamond facets as defined in EIP-2535.
*
* This interface extends the basic ERC165 mechanism to provide additional
* flexibility for querying supported interfaces, which can then be
* dynamically resolved by one of facets in a Diamond.
*/
interface IERC165Extended {
/**
* @notice Checks if the given interface ID is supported by the contract.
* @param interfaceId The ID of the interface to query.
* @return isSupported Boolean value indicating whether the interface is supported.
*/
function supportsInterfaceExtended(bytes4 interfaceId) external pure returns (bool isSupported);
}
contracts/interfaces/compiler/Command.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {CommandLibrary} from "contracts/libraries/CommandLibrary.sol";
/**
* @title Command
* @notice Contains arguments for a low-level call.
* @dev This struct allows deferring the call's execution, suspending it by passing it to another function or contract.
* @dev `target` The address to be called.
* @dev `value` Value to send in the call.
* @dev `payload` Encoded call with function selector and arguments.
*/
struct Command {
address target;
uint256 value;
bytes payload;
}
using CommandLibrary for Command global;
contracts/interfaces/compiler/adapters/IDecreasePositionEvaluator.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Asset} from "contracts/libraries/AssetLibrary.sol";
import {Command} from "../Command.sol";
import {PositionDescriptor} from "./PositionDescriptor.sol";
interface IDecreasePositionEvaluator {
/**
* @notice Request structure for decreasing a position.
* @dev `descriptor`: The [`PositionDescriptor`](/interfaces/compiler/adapters/PositionDescriptor.sol/struct.PositionDescriptor.html)
* struct.
* @dev `liquidity`: Abstract amount that can be interpreted differently in different protocols (e.g., amount of LP tokens to burn).
* @dev `minOutput`: [`Asset`](/interfaces/compliance/Asset.sol/struct.Asset.html) array with minimum amounts that must be retrieved from the position.
*/
struct DecreasePositionRequest {
PositionDescriptor descriptor;
uint256 liquidity;
Asset[] minOutput;
}
/**
* @notice Evaluate a decrease position request.
* @param _operator Address which initiated the request
* @param _request The [`DecreasePositionRequest`](#decreasepositionrequest) struct containing decrease position details.
* @return cmds_ An array of [`Command`](../../Command.sol/struct.Command.html) to execute the request.
*/
function evaluate(
address _operator,
DecreasePositionRequest calldata _request
) external returns (Command[] memory cmds_);
}
contracts/interfaces/compiler/adapters/IExchangeEvaluator.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Command} from "../Command.sol";
/**
* @title IExchangeEvaluator
* @notice Interface for compiling commands for token exchanges for different protocols.
*/
interface IExchangeEvaluator {
/**
* @notice Structure for an exchange token request.
* @dev `path`: Encoded path of tokens to follow in the exchange, including pool identifiers.
* 20 bytes(tokenA) + 4 byte(poolId_A_B) + 20 bytes(tokenB) + ...
* ... + 4 byte(poolId_N-1_N) + 20 bytes(tokenN).
* @dev `extraData`: Additional data specific to a particular protocol, such as the response from a 1Inch Exchange API.
* @dev `amountIn`: The amount of tokenA to spend.
* @dev `minAmountOut`: The minimum amount of tokenN to receive.
* @dev `recipient`: The recipient of tokenN.
*/
struct ExchangeRequest {
bytes path;
bytes extraData;
uint256 amountIn;
uint256 minAmountOut;
address recipient;
}
/**
* @notice Constructs an exchange token request.
* @param _operator Address which initiated the request
* @param _request The [`ExchangeRequest`](#exchangerequest) struct containing exchange token details.
* @return cmds_ An array of [`Command`](../../Command.sol/struct.Command.html) to execute the request.
*/
function evaluate(
address _operator,
ExchangeRequest calldata _request
) external view returns (Command[] memory cmds_);
}
contracts/interfaces/compiler/adapters/IIncreasePositionEvaluator.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Asset} from "contracts/libraries/AssetLibrary.sol";
import {Command} from "../Command.sol";
import {PositionDescriptor} from "./PositionDescriptor.sol";
interface IIncreasePositionEvaluator {
/**
* @notice Structure for an increase position request.
* @dev `descriptor`: The [`PositionDescriptor`](/interfaces/compiler/adapters/PositionDescriptor.sol/struct.PositionDescriptor.html)
* struct.
* @dev `input`: An array of [`Asset`](/interfaces/compliance/Asset.sol/struct.Asset.html) representing the token-amounts that will be added to the position.
* @dev `minLiquidityOut`: An abstract amount that can be interpreted differently in different protocols (e.g., minimum amount of LP tokens to receive).
*/
struct IncreasePositionRequest {
PositionDescriptor descriptor;
Asset[] input;
uint256 minLiquidityOut;
}
/**
* @notice Evaluate a increase position request.
* @param _operator Address which initiated the request
* @param _request The [`IncreasePositionRequest`](#increasepositionrequest) struct containing increase position details.
* @return cmds_ An array of [`Command`](../../Command.sol/struct.Command.html) to execute the request.
*/
function evaluate(
address _operator,
IncreasePositionRequest calldata _request
) external returns (Command[] memory cmds_);
}
contracts/interfaces/compiler/adapters/ILiquidityPoolsRepository.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
/* solhint-disable no-unused-import */
import {AlreadyUpToDate} from "contracts/interfaces/base/CommonErrors.sol";
import {
Status,
TokenIsNotSupported
} from "contracts/interfaces/compliance/IWhitelistingController.sol";
/* solhint-enable no-unused-import */
/**
* @notice Error indicating that the pool ID was not found.
* @param encodedPool The encoded pool data that was searched for.
*/
error PoolIdNotFound(bytes encodedPool);
/**
* @notice Error indicating that the pool does not exist.
* @param poolId The unique identifier of the pool that was searched for.
*/
error PoolIsNotSupported(uint256 poolId);
/**
* @notice Error indicating that the pool is suspended.
* @param poolId The unique identifier of the pool that is suspended.
*/
error PoolIsSuspended(uint256 poolId);
/**
* @title ILiquidityPoolsRepository
* @notice Interface for managing liquidity pools and their support status.
*/
interface ILiquidityPoolsRepository {
/**
* @notice Update the support status of a liquidity pool.
* @param _encodedPool The encoded pool data.
* @param _supported Whether the pool is supported or not.
* @return poolId_ The unique identifier of the pool.
* @dev Reverts with a [`PoolIdNotFound()`](/interfaces/compiler/adapters/ILiquidityPoolsRepository.sol/error.PoolIdNotFound.html)
* error if the pool does not exist.
*/
function updatePoolSupport(
bytes calldata _encodedPool,
bool _supported
) external returns (uint256 poolId_);
/**
* @notice Get the status of a specific pool.
* @param _poolId The unique identifier of the pool.
* @return status The status of the pool.
* @dev Reverts with a [`PoolIsNotSupported()`](/interfaces/compiler/adapters/ILiquidityPoolsRepository.sol/error.PoolIsNotSupported.html)
* error if the pool does not exist.
*/
function getPoolStatus(uint256 _poolId) external returns (Status status);
/**
* @notice Get the unique identifier (pool ID) of a specific pool.
* @param _encodedPool The encoded pool data.
* @return poolId_ The unique identifier of the pool.
* @dev Reverts with a [`PoolIsNotSupported()`](/interfaces/compiler/adapters/ILiquidityPoolsRepository.sol/error.PoolIsNotSupported.html)
* error if the pool does not exist.
*/
function getPoolId(bytes calldata _encodedPool) external view returns (uint256 poolId_);
}
contracts/interfaces/compiler/adapters/PositionDescriptor.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
// TODO CRYPTO-145: Possibly move into appropriate interface?
/**
* @notice Used to determine the required position for an operation.
* @dev `poolId`: An identifier that is unique within a single protocol.
* @dev `extraData`: Additional data used to specify the position, for example
* this is used in OneInchV5Evaluator to pass swap tx generated via 1inch API.
*/
struct PositionDescriptor {
uint256 poolId;
bytes extraData;
}
contracts/interfaces/compiler/adapters/index.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {
IDecreasePositionEvaluator
} from "contracts/interfaces/compiler/adapters/IDecreasePositionEvaluator.sol";
import {IExchangeEvaluator} from "contracts/interfaces/compiler/adapters/IExchangeEvaluator.sol";
import {
IIncreasePositionEvaluator
} from "contracts/interfaces/compiler/adapters/IIncreasePositionEvaluator.sol";
import {
AlreadyUpToDate,
ILiquidityPoolsRepository,
PoolIdNotFound,
PoolIsNotSupported,
PoolIsSuspended,
Status,
TokenIsNotSupported
} from "contracts/interfaces/compiler/adapters/ILiquidityPoolsRepository.sol";
import {PositionDescriptor} from "contracts/interfaces/compiler/adapters/PositionDescriptor.sol";
contracts/interfaces/compliance/Asset.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {AssetLibrary} from "contracts/libraries/AssetLibrary.sol";
/**
* @title Asset
* @dev Represents an asset with its token address and the amount.
* @param token The address of the asset's token.
* @param amount The amount of the asset.
*/
struct Asset {
address token;
uint256 amount;
}
using AssetLibrary for Asset global;
contracts/interfaces/compliance/IWhitelistingController.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {IERC165Extended} from "../base/IERC165Extended.sol";
import {IWhitelistingControllerAgreement} from "./IWhitelistingControllerAgreement.sol";
/**
* @title Status
* @notice Enum representing status of a record (e.g., token, protocol, operator)
* used for operation validation.
* @notice Validators must adhere to the following rules for different operations and contexts:
* 1) For exchanges: `operator`, `pool`, and `input token` *MAY* be either supported or suspended, but the `output token` *MUST* be supported.
* 2) For deposits: `operator`, `pool`, and every `token` in the `pool` *MUST* be supported.
* 3) For withdrawals: `operator`, `pool`, and each `token` *MAY* be either supported or suspended.
*
* @dev **Note** that deposit denotes **all** ways of acquiring liquidity such
* as token deposit, LP tokens stake, NFT mint etc.
*/
enum Status {
Undefined,
Supported,
Suspended
}
/**
* @title WhitelistingAddressRecord
* @notice A struct to store an address and its support status.
* @dev This struct stores an address and its support status.
* @dev `source`: The address to be stored.
* @dev `supported`: Indicates whether the address is supported or not.
*/
struct WhitelistingAddressRecord {
address source;
bool supported;
}
/**
* @title WhitelistingTokenRecord
* @notice This struct stores an address and its support status for whitelisting, collateral and leverage.
* @dev `source`: The address of the token.
* @dev `supported`: Whether the token can be received from a protocol trades.
*/
struct WhitelistingTokenRecord {
address source;
bool supported;
}
/**
* @title TreasuryStorage
* @notice ERC-7201 namespaced storage for the protocol treasury address.
* @dev `treasury`: The address that receives protocol fees on close.
*/
struct TreasuryStorage {
address treasury;
}
/**
* @notice An error indicating that a token is not supported by the whitelisting controller.
* @dev This error is thrown when an unsupported token is used.
* @dev `token`: The address of the unsupported token.
*/
error TokenIsNotSupported(address token);
/**
* @notice An error indicating that a token is suspended by the whitelisting controller.
* @dev This error is thrown when a suspended token is used.
* @dev `token`: The address of the suspended token.
*/
error TokenIsSuspended(address token);
/**
* @notice An error indicating that an operator is not supported by the whitelisting controller.
* @dev This error is thrown when an unsupported operator is used.
* @dev `operator`: The address of the unsupported operator.
*/
error OperatorIsNotSupported(address operator);
/**
* @notice An error indicating that an operator is suspended by the whitelisting controller.
* @dev This error is thrown when a suspended operator is used.
* @dev `operator`: The address of the suspended operator.
*/
error OperatorIsSuspended(address operator);
/**
* @notice An error indicating that a protocol is not supported by the whitelisting controller.
* @dev This error is thrown when an unsupported protocol is used.
* @dev `protocol`: The identification string of the unsupported protocol.
*/
error ProtocolIsNotSupported(bytes31 protocolNameHash);
/**
* @notice An error indicating that a protocol is suspended by the whitelisting controller.
* @dev This error is thrown when a suspended protocol is used.
* @dev `protocol`: The identification string of the unsupported protocol.
*/
error ProtocolIsSuspended(bytes31 protocolNameHash);
interface ITenant {
function factory() external view returns (address);
}
/**
* @title IWhitelistingController
* @notice Interface for managing whitelisting of tokens, protocols, and operators.
*/
interface IWhitelistingController is IWhitelistingControllerAgreement, IERC165Extended {
/**
* @dev Emitted when the support status of a protocol changes.
* @dev `protocol`: The identification string of the protocol.
* @dev `supported`: Whether the protocol is supported or not.
*/
event ProtocolSupportChanged(string indexed protocol, bool supported);
/**
* @dev Emitted when the support status of a token changes.
* @dev `token`: The address of the token.
* @dev `supported`: Whether the token is supported or not.
*/
event TokenSupportChanged(address indexed token, bool supported);
/**
* @dev Emitted when the support status of an operator changes for a specific protocol.
* @dev `protocol`: The identification string of the protocol.
* @dev `operator`: The address of the operator.
* @dev `supported`: Whether the operator is supported or not.
*/
event OperatorSupportChanged(string indexed protocol, address indexed operator, bool supported);
/**
* @dev Emitted when the protocol treasury address is changed.
* @dev `previousTreasury`: The treasury address before the change.
* @dev `newTreasury`: The treasury address after the change.
*/
event TreasuryChanged(address indexed previousTreasury, address indexed newTreasury);
/**
* @notice Reverts when the agreement was deployed by a different factory version.
* @dev This error is used by the `onlyAgreementFactory` modifier to prevent
* `addTokens` and `addOperators` calls from wrong factory.
* @param factory The address of the factory attempting to interact.
* @param agreement The agreement contract whose associated factory version did not match the caller.
*/
error AgreementFactoryVersionMismatch(address factory, address agreement);
/**
* @notice Reverts when the caller contract supports a prohibited interface.
* @dev This error is used by the `notMarginAccount` modifier to prevent
* function calls from contracts that implement the `IAccount` interface.
* @param caller The address of the caller contract
*/
error CallerSupportsForbiddenInterface(address caller);
/**
* @notice An error indicating that the provided address is not a valid token address.
* @dev This error is thrown when the address does not conform to the expected token interface.
* @param token The address that failed the token validation check.
*/
error InvalidTokenAddress(address token);
/**
* @notice Update the support status of multiple tokens.
* @dev Emits a [`TokenSupportChanged()`](#tokensupportchanged) event for each token whose status changed.
* @dev Reverts with an [`AlreadyUpToDate()`](/interfaces/base/CommonErrors.sol/error.AlreadyUpToDate.html)
* error if no token status changed.
* @param _tokens An array of [`WhitelistingTokenRecord`](./struct.WhitelistingTokenRecord.html)
* structs containing token addresses and support.
*/
function updateTokensSupport(WhitelistingTokenRecord[] calldata _tokens) external;
/**
* @notice Update the support status of a protocol.
* @dev Emits a [`ProtocolSupportChanged()`](#protocolsupportchanged) event.
* @dev Reverts with an [`AlreadyUpToDate()`](/interfaces/base/CommonErrors.sol/error.AlreadyUpToDate.html)
* error if protocol status is up to date.
* @param _protocol The identification string of the protocol.
* @param _supported Whether the protocol is supported or not.
*/
function updateProtocolSupport(string calldata _protocol, bool _supported) external;
/**
* @notice Update the support status of multiple operators for a specific protocol.
* @dev Emits a [`OperatorSupportChanged()`](#operatorsupportchanged) event for each token whose status changed.
* @dev Reverts with an [`AlreadyUpToDate()`](/interfaces/base/CommonErrors.sol/error.AlreadyUpToDate.html)
* error if no operator status changed.
* @param _protocol The identification string of the protocol.
* @param _operators An array of `WhitelistingAddressRecord` structs containing operator addresses and support statuses.
*/
function updateOperatorsSupport(
string calldata _protocol,
WhitelistingAddressRecord[] calldata _operators
) external;
/**
* @notice Sets the protocol treasury address.
* @dev Only callable by an account with `ARKIS_SECURITY_OFFICER_ROLE`.
* Emits a [`TreasuryChanged()`](#treasurychanged) event.
* @param newTreasury The new treasury address.
*/
function setTreasury(address newTreasury) external;
/**
* @notice Returns the role identifier required to manage all master set whitelists.
* @return A bytes32 value representing the ARKIS_WHITELIST_OFFICER_ROLE.
*/
/* solhint-disable-next-line func-name-mixedcase*/
function ARKIS_WHITELIST_OFFICER_ROLE() external view returns (bytes32);
/**
* @notice Returns the support status of a token.
* @param _token The address of the token.
* @return The [`Status`](./enum.Status.html) of the token.
*/
function getTokenStatus(address _token) external view returns (Status);
/**
* @notice Checks whether a specific token is supported by a tenant.
* @dev This function returns a boolean indicating if the given token is supported by the specified tenant.
* @param tenant The address of the tenant to check.
* @param token The address of the token to check for support.
* @return A boolean value indicating whether the token is supported by the tenant.
*/
function getTokenSupport(address tenant, address token) external view returns (bool);
/**
* @notice Retrieves the list of tokens supported by a specific tenant.
* @dev This function returns an array of token addresses that are supported by the specified tenant.
* @param tenant The address of the tenant whose supported tokens are to be retrieved.
* @return An array of addresses representing the tokens supported by the tenant.
*/
function getTokens(address tenant) external view returns (address[] memory);
/**
* @notice Returns the support status of a protocol.
* @param protocol The identification string of the protocol.
* @return The [`Status`](./enum.Status.html)
* of the protocol.
*/
function getProtocolStatus(string calldata protocol) external view returns (Status);
/**
* @notice Returns the support status of an operator for a specific protocol.
* @param _operator The address of the operator.
* @return operatorStatus_ The [`Status`](./enum.Status.html)
* of the operator.
* @return protocolStatus_ The [`Status`](./enum.Status.html)
* of the protocol.
*/
function getOperatorStatus(
address _operator
) external view returns (Status operatorStatus_, Status protocolStatus_);
/**
* @notice Returns role identifier for unpause operators
* @return bytes32 keccak256 hash of ARKIS_SECURITY_OFFICER_ROLE
*/
/* solhint-disable-next-line func-name-mixedcase*/
function ARKIS_SECURITY_OFFICER_ROLE() external view returns (bytes32);
/**
* @notice Returns the protocol treasury address that receives protocol fees on close.
* @return The treasury address.
*/
function treasury() external view returns (address);
}
contracts/interfaces/compliance/IWhitelistingControllerAgreement.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
/**
* @title IWhitelistingControllerAgreement
* @notice Interface for managing whitelisting of tokens and operators for Agreements.
*/
interface IWhitelistingControllerAgreement {
/**
* @notice Emitted when a new token is added for a specific tenant.
* @param tenant The address of the tenant to whom the token is added.
* @param token The address of the token that has been added.
*/
event TokenAdded(address tenant, address token);
/**
* @notice Emitted when a new operator is added for a specific tenant.
* @param tenant The address of the tenant to whom the operator is added.
* @param operator The address of the operator that has been added.
*/
event OperatorAdded(address tenant, address operator);
/**
* @notice Adds a list of tokens to the specified tenant.
* @param tenant The address of the tenant to which the tokens will be added.
* @param tokens An array of addresses representing the tokens to be added.
* @dev This function can be used to update the list of supported tokens for a given tenant.
*/
function addTokens(address tenant, address[] calldata tokens) external;
/**
* @notice Adds a list of operators to the specified tenant.
* @param tenant The address of the tenant to which the operators will be added.
* @param operators An array of addresses representing the operators to be added.
* @dev This function updates the list of authorized operators for a given tenant.
*/
function addOperators(address tenant, address[] calldata operators) external;
/**
* @notice Returns the address of the agreement factory contract.
* @return The address of the agreement factory.
* @dev The agreement factory is used to create and manage agreements.
*/
function agreementFactory() external view returns (address);
/**
* @notice Returns the address of the agreement V2 factory contract.
* @return The address of the agreement V2 factory.
* @dev The agreement V2 factory is used to create and manage agreements V2.
*/
function agreementV2Factory() external view returns (address);
/**
* @notice Checks if a specific token is supported for a given tenant.
* @param tenant The address of the tenant whose supported tokens are being queried.
* @param token The address of the token to check for support.
* @return A boolean indicating whether the token is supported by the tenant.
* @dev This function will return `true` if the token is supported, and `false` otherwise.
*/
function getTokenSupport(address tenant, address token) external view returns (bool);
/**
* @notice Retrieves a list of tokens supported by a specific tenant.
* @param tenant The address of the tenant whose supported tokens are being queried.
* @return An array of token addresses supported by the specified tenant.
* @dev This function returns an array containing the addresses of tokens that the tenant supports.
* It is a view function and does not modify the contract state.
*/
function getTokens(address tenant) external view returns (address[] memory);
/**
* @notice Checks if a specific operator is supported by a given tenant.
* @param tenant The address of the tenant whose supported operators are being queried.
* @param operator The address of the operator to check for support.
* @return A boolean value indicating whether the operator is supported by the tenant.
* @dev This function returns `true` if the operator is supported by the specified tenant, and `false` otherwise.
* It is a view function and does not modify the contract state.
*/
function getOperatorSupport(address tenant, address operator) external view returns (bool);
/**
* @notice Retrieves the list of operators associated with a specific tenant.
* @param tenant The address of the tenant whose operators are being queried.
* @return A dynamically-sized array of addresses representing the operators associated with the tenant.
* @dev This function is a view function and does not modify the contract state.
*/
function getOperators(address tenant) external view returns (address[] memory);
}
contracts/interfaces/compliance/internal/curveFi/ICurveFiGauge.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
/* solhint-disable func-name-mixedcase, var-name-mixedcase, func-param-name-mixedcase */
interface ICurveFiGauge {
/// @param _value Amount to stake
/// @dev Stakes _value lp tokens to the gauge
function deposit(uint256 _value) external;
/// @param _value Amount to unstake
/// @dev Unstakes _value lp tokens from the gauge
function withdraw(uint256 _value) external;
/// @return Address of the lp token which you can stake to this gauge
function lp_token() external view returns (address);
/// @return _account's lp balance on the gauge
function balanceOf(address _account) external view returns (uint256);
}
/* solhint-enable func-name-mixedcase, var-name-mixedcase, func-param-name-mixedcase */
contracts/interfaces/compliance/internal/curveFi/ICurveFiMinter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
interface ICurveFiMinter {
/// @param _gauge Address of the gauge in which tokens was staked
/// @dev Claims all rewards from gauge staking
function mint(address _gauge) external;
}
contracts/interfaces/compliance/internal/curveFi/ICurveFiPool.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
/* solhint-disable func-name-mixedcase, var-name-mixedcase, func-param-name-mixedcase */
interface ICurveFiPool {
/**
*
*
* Liquidity
*
*
**/
/**
* @param _deposit_amounts List of amounts of underlying coins to deposit. Amounts correspond to the tokens at the same index locations within Factory.get_underlying_coins.
* @param _min_mint_amount Minimum amount of LP tokens to mint from the deposit.
**/
function add_liquidity(uint256[4] calldata _deposit_amounts, uint256 _min_mint_amount) external;
/**
* @param _deposit_amounts List of amounts of underlying coins to deposit. Amounts correspond to the tokens at the same index locations within Factory.get_underlying_coins.
* @param _min_mint_amount Minimum amount of LP tokens to mint from the deposit.
**/
function add_liquidity(uint256[3] calldata _deposit_amounts, uint256 _min_mint_amount) external;
/**
* @param _deposit_amounts List of amounts of underlying coins to deposit. Amounts correspond to the tokens at the same index locations within Factory.get_underlying_coins.
* @param _min_mint_amount Minimum amount of LP tokens to mint from the deposit.
**/
function add_liquidity(uint256[2] calldata _deposit_amounts, uint256 _min_mint_amount) external;
/**
* @param _burn_amount Quantity of LP tokens to burn in the withdrawal. Amounts correspond to the tokens at the same index locations within Factory.get_underlying_coins.
* @param _min_amounts Minimum amounts of underlying coins to receive.
**/
function remove_liquidity(uint256 _burn_amount, uint256[4] calldata _min_amounts) external;
/**
* @param _burn_amount Quantity of LP tokens to burn in the withdrawal. Amounts correspond to the tokens at the same index locations within Factory.get_underlying_coins.
* @param _min_amounts Minimum amounts of underlying coins to receive.
**/
function remove_liquidity(uint256 _burn_amount, uint256[3] calldata _min_amounts) external;
/**
* @param _burn_amount Quantity of LP tokens to burn in the withdrawal. Amounts correspond to the tokens at the same index locations within Factory.get_underlying_coins.
* @param _min_amounts Minimum amounts of underlying coins to receive.
**/
function remove_liquidity(uint256 _burn_amount, uint256[2] calldata _min_amounts) external;
/**
* @param _burn_amount Amount of LP tokens to burn in the withdrawal.
* @param i Index value of the coin to withdraw. Can be found using the coins getter method.
* @param _min_received Minimum amount of the coin to receive
**/
function remove_liquidity_one_coin(
uint256 _burn_amount,
int128 i,
uint256 _min_received
) external;
/**
* @param _burn_amount Amount of LP tokens to burn in the withdrawal.
* @param i Index value of the coin to withdraw. Can be found using the coins getter method.
* @param _min_received Minimum amount of the coin to receive
**/
function remove_liquidity_one_coin(
uint256 _burn_amount,
uint256 i,
uint256 _min_received
) external;
/// @notice Withdraw coins from the pool in an imbalanced amount
/// @param _amounts List of amounts of underlying coins to withdraw
/// @param _max_burn_amount Maximum amount of LP token to burn in the withdrawal
function remove_liquidity_imbalance(
uint256[4] calldata _amounts,
uint256 _max_burn_amount
) external;
/// @notice Withdraw coins from the pool in an imbalanced amount
/// @param _amounts List of amounts of underlying coins to withdraw
/// @param _max_burn_amount Maximum amount of LP token to burn in the withdrawal
function remove_liquidity_imbalance(
uint256[3] calldata _amounts,
uint256 _max_burn_amount
) external;
/// @notice Withdraw coins from the pool in an imbalanced amount
/// @param _amounts List of amounts of underlying coins to withdraw
/// @param _max_burn_amount Maximum amount of LP token to burn in the withdrawal
function remove_liquidity_imbalance(
uint256[2] calldata _amounts,
uint256 _max_burn_amount
) external;
/**
*
*
* Swaps
*
*
**/
/**
* Perform an exchange between two coins.
* @param _i Index value for the coin to send
* @param _j Index value of the coin to receive
* @param _dx Amount of i being exchanged
* @param _min_dy Minimum amount of j to receive
**/
function exchange(int128 _i, int128 _j, uint256 _dx, uint256 _min_dy) external payable;
/**
* Perform an exchange between two coins.
* @param _i Index value for the coin to send
* @param _j Index value of the coin to receive
* @param _dx Amount of i being exchanged
* @param _min_dy Minimum amount of j to receive
* @param _use_eth Do use eth instead of weth
**/
function exchange(
uint256 _i,
uint256 _j,
uint256 _dx,
uint256 _min_dy,
bool _use_eth
) external payable;
/**
* Perform an exchange between two coins.
* @param _i Index value for the coin to send
* @param _j Index value of the coin to receive
* @param _dx Amount of i being exchanged
* @param _min_dy Minimum amount of j to receive
* @param _use_eth Do use eth instead of weth
* @param _recipient An address that will receive the `_j` coin
* @return dy_ The amount of `_j` received in the exchange.
**/
function exchange(
uint256 _i,
uint256 _j,
uint256 _dx,
uint256 _min_dy,
bool _use_eth,
address _recipient
) external payable returns (uint256 dy_);
/**
* Perform an exchange between two underlying coins.
* @param _i: Index value of the underlying token to send.
* @param _j: Index value of the underlying token to receive.
* @param _dx: The amount of i being exchanged.
* @param _min_dy: The minimum amount of j to receive. If the swap would result in less, the transaction will revert.
* @param _receiver: An optional address that will receive j. If not given, defaults to the caller.
* @return dy_ The amount of j received in the exchange.
**/
function exchange_underlying(
int128 _i,
int128 _j,
uint256 _dx,
uint256 _min_dy,
address _receiver
) external returns (uint256 dy_);
/**
*
*
* Getters
*
*
**/
/**
* Get the amount of coin j one would receive for swapping _dx of coin i
* @param _i Index value for the coin to send
* @param _j Index value of the coin to receive
* @param _dx Amount of i being exchanged
**/
function get_dy(int128 _i, int128 _j, uint256 _dx) external view returns (uint256 dy_);
/**
* Get the amount of coin j one would receive for swapping _dx of coin i
* @param _i Index value for the coin to send
* @param _j Index value of the coin to receive
* @param _dx Amount of i being exchanged
**/
function get_dy(uint256 _i, uint256 _j, uint256 _dx) external view returns (uint256 dy_);
/**
* Get the amount received (“dy”) when swapping between two underlying assets within the pool.
* @param _i Index value for the coin to send
* @param _j Index value of the coin to receive
* @param _dx The amount of j received.
**/
function get_dy_underlying(
int128 _i,
int128 _j,
uint256 _dx
) external view returns (uint256 dy_);
/**
* Get the amount received (“dy”) when swapping between two underlying assets within the pool.
* @param _i Index value for the coin to send
* @param _j Index value of the coin to receive
* @param _dx The amount of j received.
**/
function get_dy_underlying(
uint256 _i,
uint256 _j,
uint256 _dx
) external view returns (uint256 dy_);
/**
* @param _amounts Amount of each coin being deposited. Amounts correspond to the tokens at the same index locations within coins.
* @param _is_deposit set True for deposits, False for withdrawals.
* @return The expected amount of LP tokens minted or burned.
**/
function calc_token_amount(
uint256[4] calldata _amounts,
bool _is_deposit
) external view returns (uint256);
/**
* @param _amounts Amount of each coin being deposited. Amounts correspond to the tokens at the same index locations within coins.
* @param _is_deposit set True for deposits, False for withdrawals.
* @return The expected amount of LP tokens minted or burned.
**/
function calc_token_amount(
uint256[3] calldata _amounts,
bool _is_deposit
) external view returns (uint256);
/**
* @param _amounts Amount of each coin being deposited. Amounts correspond to the tokens at the same index locations within coins.
* @return The expected amount of LP tokens minted or burned.
**/
function calc_token_amount(uint256[2] calldata _amounts) external view returns (uint256);
/**
* @param _amounts Amount of each coin being deposited. Amounts correspond to the tokens at the same index locations within coins.
* @param _is_deposit set True for deposits, False for withdrawals.
* @return The expected amount of LP tokens minted or burned.
**/
function calc_token_amount(
uint256[2] calldata _amounts,
bool _is_deposit
) external view returns (uint256);
/**
* @param _burn_amount Amount of LP tokens to burn in the withdrawal.
* @param i Index value of the underlying coin to withdraw. Can be found using the coins getter method.
* @return The expected amount of coin received.
**/
function calc_withdraw_one_coin(
uint256 _burn_amount,
uint256 i
) external view returns (uint256);
function calc_withdraw_one_coin(uint256 _burn_amount, int128 i) external view returns (uint256);
/**
* @param i Index of the token of this pool
* @return Address of the token of i index
**/
function coins(uint256 i) external view returns (address);
function underlying_coins(uint256 i) external view returns (address);
function balances(uint256 i) external view returns (uint256);
function mid_fee() external view returns (uint256);
}
/* solhint-enable func-name-mixedcase, var-name-mixedcase, func-param-name-mixedcase */
contracts/interfaces/compliance/internal/curveFi/ICurveFiRouter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
/* solhint-disable func-name-mixedcase, var-name-mixedcase, func-param-name-mixedcase */
interface ICurveFiRouter {
function exchange_multiple(
address[9] calldata _route,
uint256[3][4] calldata _swap_params,
uint256 _amount,
uint256 _expected,
address[4] calldata _pools,
address _receiver
) external payable returns (uint256);
}
/* solhint-enable func-name-mixedcase, var-name-mixedcase, func-param-name-mixedcase */
contracts/interfaces/compliance/internal/curveFi/ICurveFiZapper.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
/* solhint-disable func-name-mixedcase, var-name-mixedcase, func-param-name-mixedcase */
/// @notice Deposit zapper contract for metapools
interface ICurveFiZapper {
/// @notice Wrap underlying coins and deposit them into `_pool`
/// @param _pool Address of the pool to deposit into
/// @param _deposit_amounts List of amounts of underlying coins to deposit
/// @param _min_mint_amount Minimum amount of LP tokens to mint from the deposit
function add_liquidity(
address _pool,
uint256[4] calldata _deposit_amounts,
uint256 _min_mint_amount
) external;
/// @notice Withdraw and unwrap coins from the pool
/// @dev Withdrawal amounts are based on current deposit ratios
/// @param _pool Address of the pool to deposit into
/// @param _burn_amount Quantity of LP tokens to burn in the withdrawal
/// @param _min_amounts Minimum amounts of underlying coins to receive
function remove_liquidity(
address _pool,
uint256 _burn_amount,
uint256[4] calldata _min_amounts
) external;
/// @notice Withdraw and unwrap coins from the pool
/// @dev Withdrawal amounts are based on current deposit ratios
/// @param _pool Address of the pool to deposit into
/// @param _burn_amount Quantity of LP tokens to burn in the withdrawal
/// @param _min_amounts Minimum amounts of underlying coins to receive
/// @param _receiver Address that receives the LP tokens
function remove_liquidity(
address _pool,
uint256 _burn_amount,
uint256[4] calldata _min_amounts,
address _receiver
) external;
/// @notice Withdraw and unwrap a single coin from the pool
/// @param _pool Address of the pool to deposit into
/// @param _burn_amount Amount of LP tokens to burn in the withdrawal
/// @param i Index value of the coin to withdraw
/// @param _min_amount Minimum amount of underlying coin to receive
function remove_liquidity_one_coin(
address _pool,
uint256 _burn_amount,
int128 i,
uint256 _min_amount
) external;
/// @notice Withdraw and unwrap a single coin from the pool
/// @param _pool Address of the pool to deposit into
/// @param _burn_amount Amount of LP tokens to burn in the withdrawal
/// @param i Index value of the coin to withdraw
/// @param _min_amount Minimum amount of underlying coin to receive
/// @param _receiver Address that receives the LP tokens
function remove_liquidity_one_coin(
address _pool,
uint256 _burn_amount,
int128 i,
uint256 _min_amount,
address _receiver
) external;
/// @notice Withdraw coins from the pool in an imbalanced amount
/// @param _pool Address of the pool to deposit into
/// @param _amounts List of amounts of underlying coins to withdraw
/// @param _max_burn_amount Maximum amount of LP token to burn in the withdrawal
function remove_liquidity_imbalance(
address _pool,
uint256[4] memory _amounts,
uint256 _max_burn_amount
) external;
/// @notice Withdraw coins from the pool in an imbalanced amount
/// @param _pool Address of the pool to deposit into
/// @param _amounts List of amounts of underlying coins to withdraw
/// @param _max_burn_amount Maximum amount of LP token to burn in the withdrawal
/// @param _receiver Address that receives the LP tokens
function remove_liquidity_imbalance(
address _pool,
uint256[4] memory _amounts,
uint256 _max_burn_amount,
address _receiver
) external;
function calc_token_amount(address, uint256[4] calldata, bool) external view returns (uint256);
}
/* solhint-enable func-name-mixedcase, var-name-mixedcase, func-param-name-mixedcase */
contracts/interfaces/compliance/internal/curveFi/index.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {ICurveFiGauge} from "./ICurveFiGauge.sol";
import {ICurveFiMinter} from "./ICurveFiMinter.sol";
import {ICurveFiPool} from "./ICurveFiPool.sol";
import {ICurveFiRouter} from "./ICurveFiRouter.sol";
import {ICurveFiZapper} from "./ICurveFiZapper.sol";
contracts/libraries/Address.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
library Address {
address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
function set(bytes32 _slot, address _value) internal {
assembly {
sstore(_slot, _value)
}
}
function get(bytes32 _slot) internal view returns (address result_) {
assembly {
result_ := sload(_slot)
}
}
function isEth(address _token) internal pure returns (bool) {
return _token == ETH || _token == address(0);
}
function sort(address _a, address _b) internal pure returns (address, address) {
return _a < _b ? (_a, _b) : (_b, _a);
}
function sort(address[4] memory _array) internal pure returns (address[4] memory _sorted) {
// Sorting network for the array of length 4
(_sorted[0], _sorted[1]) = sort(_array[0], _array[1]);
(_sorted[2], _sorted[3]) = sort(_array[2], _array[3]);
(_sorted[0], _sorted[2]) = sort(_sorted[0], _sorted[2]);
(_sorted[1], _sorted[3]) = sort(_sorted[1], _sorted[3]);
(_sorted[1], _sorted[2]) = sort(_sorted[1], _sorted[2]);
}
}
contracts/libraries/AssetLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol";
import {AmountMustNotBeZero} from "contracts/interfaces/base/CommonErrors.sol";
import {Asset} from "contracts/interfaces/compliance/Asset.sol";
import {Address} from "./Address.sol";
library AssetLibrary {
using SafeTransferLib for address;
using Address for address;
error NotEnoughReceived(address token, uint256 expected, uint256 received);
function forward(Asset calldata self, address _to) internal {
if (self.amount == 0) revert AmountMustNotBeZero(self.token);
if (self.token.isEth()) _to.safeTransferETH(self.amount);
else self.token.safeTransferFrom(msg.sender, _to, self.amount);
}
function approve(Asset calldata self, address to) internal {
self.token.safeApprove(to, self.amount);
}
function receiveFrom(Asset storage self, address from) internal {
self.token.safeTransferFrom(from, address(this), self.amount);
}
function receiveFrom(Asset calldata self, address from) internal {
self.token.safeTransferFrom(from, address(this), self.amount);
}
function enforceReceived(Asset calldata self) internal view {
if (self.amount == 0) revert AmountMustNotBeZero(self.token);
uint256 balance = self.token.isEth()
? address(this).balance
: self.token.balanceOf(address(this));
if (balance < self.amount) revert NotEnoughReceived(self.token, self.amount, balance);
}
}
contracts/libraries/CommandLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Command} from "contracts/interfaces/compiler/Command.sol";
import {SafeCall} from "contracts/libraries/SafeCall.sol";
/**
* @notice Utility to convert often-used methods into a Command object
*/
library CommandPresets {
function approve(
address _token,
address _to,
uint256 _amount
) internal pure returns (Command[] memory result_) {
result_ = new Command[](2);
result_[0] = Command(_token, 0, abi.encodeCall(IERC20.approve, (_to, 0)));
result_[1] = Command(_token, 0, abi.encodeCall(IERC20.approve, (_to, _amount)));
}
function transfer(
address _token,
address _to,
uint256 _amount
) internal pure returns (Command memory cmd_) {
cmd_.target = _token;
cmd_.payload = abi.encodeCall(IERC20.transfer, (_to, _amount));
}
}
library CommandExecutor {
using SafeCall for Command[];
function execute(Command[] calldata _cmds) external {
_cmds.safeCallAll();
}
}
library CommandLibrary {
using CommandLibrary for Command[];
function last(Command[] memory _self) internal pure returns (Command memory) {
return _self[_self.length - 1];
}
function asArray(Command memory _self) internal pure returns (Command[] memory result_) {
result_ = new Command[](1);
result_[0] = _self;
}
function append(
Command[] memory _self,
Command[] memory _cmds
) internal pure returns (Command[] memory result_) {
result_ = new Command[](_self.length + _cmds.length);
uint256 i;
for (; i < _self.length; i++) {
result_[i] = _self[i];
}
for (; i < result_.length; i++) {
result_[i] = _cmds[i - _self.length];
}
}
function push(
Command[] memory _self,
Command memory _cmd
) internal pure returns (Command[] memory result_) {
result_ = new Command[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
result_[i] = _self[i];
}
result_[_self.length] = _cmd;
}
function populateWithApprove(
Command memory _self,
address _token,
uint256 _amount
) internal pure returns (Command[] memory result_) {
if (_amount != 0) {
result_ = CommandPresets.approve(_token, _self.target, _amount).push(_self);
} else {
result_ = _self.asArray();
}
}
}
contracts/libraries/SafeCall.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {Command} from "contracts/interfaces/compiler/Command.sol";
/**
* @notice Safe methods performing a low-level calls that revert
* if the call was not successful
*/
library SafeCall {
using Address for address;
function safeCallAll(Command[] memory _cmds) internal {
for (uint256 i; i < _cmds.length; i++) {
safeCall(_cmds[i]);
}
}
function safeCall(Command memory _cmd) internal returns (bytes memory result_) {
result_ = safeCall(_cmd.target, _cmd.value, _cmd.payload);
}
function safeCall(address _target, bytes memory _data) internal returns (bytes memory result_) {
result_ = safeCall(_target, 0, _data);
}
function safeCall(
address _target,
uint256 _value,
bytes memory _data
) internal returns (bytes memory result_) {
result_ = _target.functionCallWithValue(_data, _value);
}
function safeDelegateCall(
address _target,
bytes memory _data
) internal returns (bytes memory result_) {
result_ = _target.functionDelegateCall(_data);
}
}
solady/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Caution! This library won't check that a token has code, responsibility is delegated to the caller.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH
/// that disallows any storage writes.
uint256 internal constant _GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
/// Multiply by a small constant (e.g. 2), if needed.
uint256 internal constant _GAS_STIPEND_NO_GRIEF = 100000;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` (in wei) ETH to `to`.
/// Reverts upon failure.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and check if it succeeded or not.
if iszero(call(gas(), to, amount, 0, 0, 0, 0)) {
// Store the function selector of `ETHTransferFailed()`.
mstore(0x00, 0xb12d13eb)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
/// The `gasStipend` can be set to a low enough value to prevent
/// storage writes or gas griefing.
///
/// If sending via the normal procedure fails, force sends the ETH by
/// creating a temporary contract which uses `SELFDESTRUCT` to force send the ETH.
///
/// Reverts if the current contract has insufficient balance.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
// If insufficient balance, revert.
if lt(selfbalance(), amount) {
// Store the function selector of `ETHTransferFailed()`.
mstore(0x00, 0xb12d13eb)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
// Transfer the ETH and check if it succeeded or not.
if iszero(call(gasStipend, to, amount, 0, 0, 0, 0)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
// We can directly use `SELFDESTRUCT` in the contract creation.
// Compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758
if iszero(create(amount, 0x0b, 0x16)) {
// For better gas estimation.
if iszero(gt(gas(), 1000000)) { revert(0, 0) }
}
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a gas stipend
/// equal to `_GAS_STIPEND_NO_GRIEF`. This gas stipend is a reasonable default
/// for 99% of cases and can be overriden with the three-argument version of this
/// function if necessary.
///
/// If sending via the normal procedure fails, force sends the ETH by
/// creating a temporary contract which uses `SELFDESTRUCT` to force send the ETH.
///
/// Reverts if the current contract has insufficient balance.
function forceSafeTransferETH(address to, uint256 amount) internal {
// Manually inlined because the compiler doesn't inline functions with branches.
/// @solidity memory-safe-assembly
assembly {
// If insufficient balance, revert.
if lt(selfbalance(), amount) {
// Store the function selector of `ETHTransferFailed()`.
mstore(0x00, 0xb12d13eb)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
// Transfer the ETH and check if it succeeded or not.
if iszero(call(_GAS_STIPEND_NO_GRIEF, to, amount, 0, 0, 0, 0)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
// We can directly use `SELFDESTRUCT` in the contract creation.
// Compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758
if iszero(create(amount, 0x0b, 0x16)) {
// For better gas estimation.
if iszero(gt(gas(), 1000000)) { revert(0, 0) }
}
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
/// The `gasStipend` can be set to a low enough value to prevent
/// storage writes or gas griefing.
///
/// Simply use `gasleft()` for `gasStipend` if you don't need a gas stipend.
///
/// Note: Does NOT revert upon failure.
/// Returns whether the transfer of ETH is successful instead.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and check if it succeeded or not.
success := call(gasStipend, to, amount, 0, 0, 0, 0)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
// Store the function selector of `transferFrom(address,address,uint256)`.
mstore(0x0c, 0x23b872dd000000000000000000000000)
if iszero(
and( // The arguments of `and` are evaluated from right to left.
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(eq(mload(0x00), 1), iszero(returndatasize())),
call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
)
) {
// Store the function selector of `TransferFromFailed()`.
mstore(0x00, 0x7939f424)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
// Store the function selector of `balanceOf(address)`.
mstore(0x0c, 0x70a08231000000000000000000000000)
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
// Store the function selector of `TransferFromFailed()`.
mstore(0x00, 0x7939f424)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
// Store the function selector of `transferFrom(address,address,uint256)`.
mstore(0x00, 0x23b872dd)
// The `amount` argument is already written to the memory word at 0x6c.
amount := mload(0x60)
if iszero(
and( // The arguments of `and` are evaluated from right to left.
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(eq(mload(0x00), 1), iszero(returndatasize())),
call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
)
) {
// Store the function selector of `TransferFromFailed()`.
mstore(0x00, 0x7939f424)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
// Store the function selector of `transfer(address,uint256)`.
mstore(0x00, 0xa9059cbb000000000000000000000000)
if iszero(
and( // The arguments of `and` are evaluated from right to left.
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(eq(mload(0x00), 1), iszero(returndatasize())),
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
// Store the function selector of `TransferFailed()`.
mstore(0x00, 0x90b8ec18)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
// Restore the part of the free memory pointer that was overwritten.
mstore(0x34, 0)
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
// Store the function selector of `TransferFailed()`.
mstore(0x00, 0x90b8ec18)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
// The `amount` argument is already written to the memory word at 0x34.
amount := mload(0x34)
// Store the function selector of `transfer(address,uint256)`.
mstore(0x00, 0xa9059cbb000000000000000000000000)
if iszero(
and( // The arguments of `and` are evaluated from right to left.
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(eq(mload(0x00), 1), iszero(returndatasize())),
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
// Store the function selector of `TransferFailed()`.
mstore(0x00, 0x90b8ec18)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
// Restore the part of the free memory pointer that was overwritten.
mstore(0x34, 0)
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
// Store the function selector of `approve(address,uint256)`.
mstore(0x00, 0x095ea7b3000000000000000000000000)
if iszero(
and( // The arguments of `and` are evaluated from right to left.
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(eq(mload(0x00), 1), iszero(returndatasize())),
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
// Store the function selector of `ApproveFailed()`.
mstore(0x00, 0x3e3f8f73)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
// Restore the part of the free memory pointer that was overwritten.
mstore(0x34, 0)
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
// Store the function selector of `balanceOf(address)`.
mstore(0x00, 0x70a08231000000000000000000000000)
amount :=
mul(
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"useLiteralContent": true
},
"optimizer": {
"runs": 1000000,
"details": {
"yulDetails": {
"optimizerSteps": "u"
}
},
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.