Verified contractPartialMIT
RangeProtocolVault
Address0xb25071dcdffb946230fe2ffceb589adace440c11
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.4
- Same code
Only this contract
Details
- Compiler
- solc 0.8.4+commit.c7e474f2
- Language
- solidity
- Optimization
- Yes, 100 runs
- EVM version
- istanbul
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 19,123,479
- Creation transaction
- 0x64987065f0…7331a82aad
- Libraries
- contracts/libraries/VaultLib.sol:VaultLib0xb0f6…754c19
35 files
- contracts/RangeProtocolVault.solmain16.32 KB
- @openzeppelin/contracts-upgradeable/interfaces/draft-IERC1822Upgradeable.sol890 B
- @openzeppelin/contracts-upgradeable/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol7.84 KB
- @openzeppelin/contracts-upgradeable/proxy/beacon/IBeaconUpgradeable.sol461 B
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol6.63 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol4.76 KB
- @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol3.09 KB
- @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol3.38 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol13.64 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol2.78 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol716 B
- @openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol2.26 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol4.59 KB
- @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol8.28 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.35 KB
- @openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol2.68 KB
- @openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol35.09 KB
- @openzeppelin/contracts/utils/Address.sol7.81 KB
- contracts/RangeProtocolVaultStorage.sol3.69 KB
- contracts/access/OwnableUpgradeable.sol3.22 KB
- contracts/errors/VaultErrors.sol834 B
- contracts/interfaces/IRangeProtocolVault.sol4.95 KB
- contracts/interfaces/IWETH9.sol283 B
- contracts/interfaces/stader/IStaderConfig.sol5.62 KB
- contracts/interfaces/stader/IStaderOracle.sol608 B
- contracts/interfaces/stader/IStaderStakePoolManager.sol2.12 KB
- contracts/libraries/DataTypes.sol1.11 KB
- contracts/libraries/VaultLib.sol43.51 KB
- contracts/pancake/FixedPoint96.sol378 B
- contracts/pancake/FullMath.sol5.64 KB
- contracts/pancake/LiquidityAmounts.sol6.33 KB
- contracts/pancake/TickMath.sol9.21 KB
- contracts/pancake/interfaces/IPancakeV3Pool.sol14.06 KB
- contracts/pancake/interfaces/callback/IPancakeV3MintCallback.sol978 B
- contracts/pancake/interfaces/callback/IPancakeV3SwapCallback.sol1.29 KB
contracts/RangeProtocolVault.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {OwnableUpgradeable} from "./access/OwnableUpgradeable.sol";
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IPancakeV3Pool} from "./pancake/interfaces/IPancakeV3Pool.sol";
import {IRangeProtocolVault} from "./interfaces/IRangeProtocolVault.sol";
import {RangeProtocolVaultStorage} from "./RangeProtocolVaultStorage.sol";
import {VaultErrors} from "./errors/VaultErrors.sol";
import {VaultLib} from "./libraries/VaultLib.sol";
/**
* @dev Mars@RangeProtocol
* @notice RangeProtocolVault is fungible vault shares contract that accepts pancake pool tokens for liquidity
* provision to the corresponding pancake v3 pool. This contract is configurable to work with any pancake v3
* pool and is initialized through RangeProtocolFactory contract's createVault function which determines
* the pool address based provided tokens addresses and fee tier.
*
* The contract allows minting and burning of vault shares where minting involves providing token0 and/or token1
* for the current set ticks (or based on ratio of token0 and token1 amounts in the vault when vault does not have an
* active position in the pancake v3 pool) and burning involves removing liquidity from the pancake v3 pool along with
* the vault's fee.
*
* The manager of the contract can remove liquidity from pancake v3 pool and deposit into a newer take range to maximise
* the profit by keeping liquidity out of the pool under high volatility periods.
*
* Part of the fee earned from pancake v3 position is paid to manager as performance fee and fee is charged on the LP's
* notional amount as managing fee.
*/
contract RangeProtocolVault is
Initializable,
UUPSUpgradeable,
ReentrancyGuardUpgradeable,
OwnableUpgradeable,
ERC20Upgradeable,
PausableUpgradeable,
IRangeProtocolVault,
RangeProtocolVaultStorage
{
address public constant staderConfig = 0x4ABEF2263d5A5ED582FC9A9789a41D85b68d69DB;
address public constant staderOracle = 0xF64bAe65f6f2a5277571143A24FaaFDFC0C2a737;
// @notice restricts the call by self. It used to restrict the allowed calls only from the VaultLib.
modifier onlyVault() {
if (msg.sender != address(this)) revert VaultErrors.OnlyVaultAllowed();
_;
}
constructor() {
_disableInitializers();
}
receive() external payable {
require(msg.sender == state.WETH9);
}
/**
* @notice initialize initializes the vault contract and is called right after proxy deployment
* by the factory contract.
* @param _pool address of the pancake v3 pool associated with vault
* @param _tickSpacing tick spacing of the pancake pool
* @param data additional config data associated with the implementation. The data type chosen is bytes
* to keep the initialize function implementation contract generic to be compatible with factory contract
*/
function initialize(
address _pool,
int24 _tickSpacing,
bytes memory data
) external override initializer {
(address manager, string memory _name, string memory _symbol, address _WETH9) = abi.decode(
data,
(address, string, string, address)
);
// reverts if manager address provided is zero.
if (manager == address(0x0)) revert VaultErrors.ZeroManagerAddress();
__UUPSUpgradeable_init();
__ReentrancyGuard_init();
__Ownable_init();
__ERC20_init(_name, _symbol);
__Pausable_init();
_transferOwnership(manager);
state.pool = IPancakeV3Pool(_pool);
state.token0 = IERC20Upgradeable(state.pool.token0());
state.token1 = IERC20Upgradeable(state.pool.token1());
state.tickSpacing = _tickSpacing;
state.factory = msg.sender;
state.WETH9 = _WETH9;
// Managing fee is 0% and performanceFee is 10% at the time vault initialization.
VaultLib.updateFees(state, 0, 1000);
}
/**
* @dev mints vault shares {amount} to {to} address.
* requirements:
* - only vault is allowed to call it (intends to be called by the library)
*/
function mint(address to, uint256 amount) external override onlyVault {
_mint(to, amount);
}
/**
* @dev burns vault shares {amount} from {from} address.
* requirements:
* - only vault is allowed to call it (intends to be called by the library)
*/
function burn(address from, uint256 amount) external override onlyVault {
_burn(from, amount);
}
/**
* @notice updateTicks it is called by the contract manager to update the ticks.
* It can only be called once total supply is zero and the vault has not active position
* in the pancake pool
* @param _lowerTick lowerTick to set
* @param _upperTick upperTick to set
*/
function updateTicks(int24 _lowerTick, int24 _upperTick) external override onlyManager {
VaultLib.updateTicks(state, _lowerTick, _upperTick);
}
/**
* @notice allows pausing of minting and burning features of the contract in the event
* any security risk is seen in the vault.
*/
function pause() external onlyManager {
_pause();
}
/**
* @notice allows unpausing of minting and burning features of the contract if they paused.
*/
function unpause() external onlyManager {
_unpause();
}
/// @notice pancakeV3MintCallback Pancake V3 callback fn, called back on pool.mint
function pancakeV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata
) external override {
VaultLib.pancakeV3MintCallback(state, amount0Owed, amount1Owed, "");
}
/// @notice pancakeV3SwapCallback Pancake v3 callback fn, called back on pool.swap
function pancakeV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata
) external override {
VaultLib.pancakeV3SwapCallback(state, amount0Delta, amount1Delta, "");
}
/**
* @notice mint mints range vault shares, fractional shares of a Pancake V3 position/strategy
* to compute the amount of tokens necessary to mint `mintAmount` see getMintAmounts
* @param mintAmount The number of shares to mint
* @param maxAmountsIn max amounts to add in token0 and token1.
* @return amount0 amount of token0 transferred from msg.sender to mint `mintAmount`
* @return amount1 amount of token1 transferred from msg.sender to mint `mintAmount`
*/
function mint(
uint256 mintAmount,
bool depositNative,
uint256[2] calldata maxAmountsIn
)
external
payable
override
nonReentrant
whenNotPaused
returns (uint256 amount0, uint256 amount1)
{
return VaultLib.mint(state, mintAmount, depositNative, maxAmountsIn);
}
/**
* @notice burn burns range vault shares (shares of a Pancake V3 position) and receive underlying
* @param burnAmount The number of shares to burn
* @param withdrawNative to withdraw amounts in native token
* @param minAmountsOut minimum amounts out
* @return amount0 amount of token0 transferred to msg.sender for burning {burnAmount}
* @return amount1 amount of token1 transferred to msg.sender for burning {burnAmount}
*/
function burn(
uint256 burnAmount,
bool withdrawNative,
uint256[2] calldata minAmountsOut
) external override nonReentrant returns (uint256 amount0, uint256 amount1) {
return VaultLib.burn(state, burnAmount, withdrawNative, minAmountsOut);
}
/**
* @notice removeLiquidity removes liquidity from pancake pool and receives underlying tokens
* in the vault contract.
* @param minAmountsOut minimum amounts to get from the pool upon removal of liquidity.
*/
function removeLiquidity(uint256[2] calldata minAmountsOut) external override onlyManager {
VaultLib.removeLiquidity(state, minAmountsOut);
}
/**
* @dev Mars@RangeProtocol
* @notice swap swaps token0 for token1 (token0 in, token1 out), or token1 for token0 (token1 in token0 out).
* Zero for one will cause the price: amount1 / amount0 lower, otherwise it will cause the price higher
* @param zeroForOne The direction of the swap, true is swap token0 for token1, false is swap token1 to token0
* @param swapAmount The exact input token amount of the swap
* @param sqrtPriceLimitX96 threshold price ratio after the swap.
* If zero for one, the price cannot be lower (swap make price lower) than this threshold value after the swap
* If one for zero, the price cannot be greater (swap make price higher) than this threshold value after the swap
* @param minAmountOut minimum amount to protect against slippage.
* @return amount0 If positive represents exact input token0 amount after this swap, msg.sender paid amount,
* or exact output token0 amount (negative), msg.sender received amount
* @return amount1 If positive represents exact input token1 amount after this swap, msg.sender paid amount,
* or exact output token1 amount (negative), msg.sender received amount
*/
function swap(
bool zeroForOne,
int256 swapAmount,
uint160 sqrtPriceLimitX96,
uint256 minAmountOut
) external override onlyManager returns (int256 amount0, int256 amount1) {
return VaultLib.swap(state, zeroForOne, swapAmount, sqrtPriceLimitX96, minAmountOut);
}
/**
* @dev Mars@RangeProtocol
* @notice addLiquidity allows manager to add liquidity into pancake pool into newer tick ranges.
* @param newLowerTick new lower tick to deposit liquidity into
* @param newUpperTick new upper tick to deposit liquidity into
* @param amount0 max amount of amount0 to use
* @param amount1 max amount of amount1 to use
* @param minAmountsIn minimum amounts to add for slippage protection
* @param maxAmountsIn maximum amounts to add for slippage protection
* @return remainingAmount0 remaining amount from amount0
* @return remainingAmount1 remaining amount from amount1
*/
function addLiquidity(
int24 newLowerTick,
int24 newUpperTick,
uint256 amount0,
uint256 amount1,
uint256[2] calldata minAmountsIn,
uint256[2] calldata maxAmountsIn
) external override onlyManager returns (uint256 remainingAmount0, uint256 remainingAmount1) {
return
VaultLib.addLiquidity(
state,
newLowerTick,
newUpperTick,
amount0,
amount1,
minAmountsIn,
maxAmountsIn
);
}
/*
* @dev Allows rebalance of the vault by manager using off-chain quote and non-pool venues.
* @param target address of the target swap venue.
* @param swapData data to send to the target swap venue.
* @param zeroForOne swap direction, true for x -> y; false for y -> x.
* @param amountIn amount of tokenIn to swap.
**/
function rebalance(
address target,
bytes calldata swapData,
bool zeroForOne,
uint256 amountIn
) external override onlyManager {
VaultLib.rebalance(state, staderOracle, target, swapData, zeroForOne, amountIn);
}
/**
* @dev Allows minting of ETHx from ETH.
* only manager can call it.
* @param amount the amount of ETH to deposit to mint ETHx.
*/
function mintETHx(uint256 amount) external override onlyManager returns (uint256 mintedETHx) {
return VaultLib.mintETHx(state, staderConfig, amount);
}
/**
* @dev pullFeeFromPool pulls accrued fee from pancake v3 pool that position has accrued since
* last collection.
*/
function pullFeeFromPool() external override onlyManager {
VaultLib.pullFeeFromPool(state);
}
/// @notice collectManager collects manager fees accrued
function collectManager() external override onlyManager {
VaultLib.collectManager(state, manager());
}
/**
* @notice updateFees allows updating of managing and performance fees
*/
function updateFees(
uint16 newManagingFee,
uint16 newPerformanceFee
) external override onlyManager {
VaultLib.updateFees(state, newManagingFee, newPerformanceFee);
}
/**
* @notice compute maximum shares that can be minted from `amount0Max` and `amount1Max`
* @param amount0Max The maximum amount of token0 to forward on mint
* @param amount1Max The maximum amount of token1 to forward on mint
* @return amount0 actual amount of token0 to forward when minting `mintAmount`
* @return amount1 actual amount of token1 to forward when minting `mintAmount`
* @return mintAmount maximum number of shares mintable
*/
function getMintAmounts(
uint256 amount0Max,
uint256 amount1Max
) external view override returns (uint256 amount0, uint256 amount1, uint256 mintAmount) {
return VaultLib.getMintAmounts(state, amount0Max, amount1Max);
}
/**
* @notice getCurrentFees returns the current uncollected fees
* @return fee0 uncollected fee in token0
* @return fee1 uncollected fee in token1
*/
function getCurrentFees() external view override returns (uint256 fee0, uint256 fee1) {
return VaultLib.getCurrentFees(state);
}
/**
* @notice getPositionID returns the position id of the vault in pancake pool
* @return positionID position id of the vault in pancake pool
*/
function getPositionID() public view override returns (bytes32 positionID) {
return VaultLib.getPositionID(state);
}
/**
* @notice compute total underlying token0 and token1 token supply at current price
* includes current liquidity invested in pancake position, current fees earned
* and any uninvested leftover (but does not include manager fees accrued)
* @return amount0Current current total underlying balance of token0
* @return amount1Current current total underlying balance of token1
*/
function getUnderlyingBalances()
public
view
override
returns (uint256 amount0Current, uint256 amount1Current)
{
return VaultLib.getUnderlyingBalances(state);
}
function getUnderlyingBalancesByShare(
uint256 shares
) external view returns (uint256 amount0, uint256 amount1) {
return VaultLib.getUnderlyingBalancesByShare(state, shares);
}
/**
* @notice _authorizeUpgrade internally called by UUPS contract to validate the upgrading operation of
* the contract.
*/
function _authorizeUpgrade(address) internal override {
if (msg.sender != state.factory) revert VaultErrors.OnlyFactoryAllowed();
}
/**
* @notice The userVault mapping is updated before the vault share tokens are transferred between the users.
* The data from this mapping is used by off-chain strategy manager. The data in this mapping does not impact
* the on-chain behaviour of vault or users' funds.
* @dev transfers userVault amounts based on the transferring user vault shares
* @param from address to transfer userVault amount from
* @param to address to transfer userVault amount to
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override {
super._beforeTokenTransfer(from, to, amount);
VaultLib._beforeTokenTransfer(state, from, to, amount);
}
}
@openzeppelin/contracts-upgradeable/interfaces/draft-IERC1822Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822ProxiableUpgradeable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
@openzeppelin/contracts-upgradeable/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts-upgradeable/proxy/beacon/IBeaconUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @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]
* ```
* 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 Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 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 functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_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 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_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() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @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 {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized < type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../extensions/draft-IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function safePermit(
IERC20PermitUpgradeable token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
}
@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCastUpgradeable {
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toUint248(uint256 value) internal pure returns (uint248) {
require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toUint240(uint256 value) internal pure returns (uint240) {
require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toUint232(uint256 value) internal pure returns (uint232) {
require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.2._
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toUint216(uint256 value) internal pure returns (uint216) {
require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toUint208(uint256 value) internal pure returns (uint208) {
require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toUint200(uint256 value) internal pure returns (uint200) {
require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toUint192(uint256 value) internal pure returns (uint192) {
require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toUint184(uint256 value) internal pure returns (uint184) {
require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toUint176(uint256 value) internal pure returns (uint176) {
require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toUint168(uint256 value) internal pure returns (uint168) {
require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toUint160(uint256 value) internal pure returns (uint160) {
require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toUint152(uint256 value) internal pure returns (uint152) {
require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toUint144(uint256 value) internal pure returns (uint144) {
require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toUint136(uint256 value) internal pure returns (uint136) {
require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v2.5._
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toUint120(uint256 value) internal pure returns (uint120) {
require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toUint112(uint256 value) internal pure returns (uint112) {
require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toUint104(uint256 value) internal pure returns (uint104) {
require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.2._
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toUint80(uint256 value) internal pure returns (uint80) {
require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toUint72(uint256 value) internal pure returns (uint72) {
require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v2.5._
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toUint56(uint256 value) internal pure returns (uint56) {
require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toUint48(uint256 value) internal pure returns (uint48) {
require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v2.5._
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toUint24(uint256 value) internal pure returns (uint24) {
require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v2.5._
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v2.5._
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*
* _Available since v3.0._
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.7._
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.7._
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*
* _Available since v3.0._
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contracts/RangeProtocolVaultStorage.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IPancakeV3Pool} from "./pancake/interfaces/IPancakeV3Pool.sol";
import {DataTypes} from "./libraries/DataTypes.sol";
import {IRangeProtocolVault} from "./interfaces/IRangeProtocolVault.sol";
/**
* @notice RangeProtocolVaultStorage a storage contract for RangeProtocolVault
*/
abstract contract RangeProtocolVaultStorage is IRangeProtocolVault {
DataTypes.State internal state;
function lowerTick() external view override returns (int24) {
return state.lowerTick;
}
function upperTick() external view override returns (int24) {
return state.upperTick;
}
function inThePosition() external view override returns (bool) {
return state.inThePosition;
}
function mintStarted() external view override returns (bool) {
return state.mintStarted;
}
function tickSpacing() external view override returns (int24) {
return state.tickSpacing;
}
function pool() external view override returns (IPancakeV3Pool) {
return state.pool;
}
function token0() external view override returns (IERC20Upgradeable) {
return state.token0;
}
function token1() external view override returns (IERC20Upgradeable) {
return state.token1;
}
function factory() external view override returns (address) {
return state.factory;
}
function managingFee() external view override returns (uint16) {
return state.managingFee;
}
function performanceFee() external view override returns (uint16) {
return state.performanceFee;
}
function managerBalance0() external view override returns (uint256) {
return state.managerBalance0;
}
function managerBalance1() external view override returns (uint256) {
return state.managerBalance1;
}
function userVaults(address user) external view override returns (DataTypes.UserVault memory) {
return state.userVaults[user];
}
function users(uint256 index) external view override returns (address) {
return state.users[index];
}
function WETH9() external view override returns (address) {
return state.WETH9;
}
/**
* @notice returns array of current user vaults. This function is only intended to be called off-chain.
* @param fromIdx start index to fetch the user vaults info from.
* @param toIdx end index to fetch the user vault to.
*/
function getUserVaults(
uint256 fromIdx,
uint256 toIdx
) external view override returns (DataTypes.UserVaultInfo[] memory) {
if (fromIdx == 0 && toIdx == 0) {
toIdx = state.users.length;
}
DataTypes.UserVaultInfo[] memory usersVaultInfo = new DataTypes.UserVaultInfo[](
toIdx - fromIdx
);
uint256 count;
for (uint256 i = fromIdx; i < toIdx; i++) {
DataTypes.UserVault memory userVault = state.userVaults[state.users[i]];
usersVaultInfo[count++] = DataTypes.UserVaultInfo({
user: state.users[i],
token0: userVault.token0,
token1: userVault.token1
});
}
return usersVaultInfo;
}
/**
* @dev returns the length of users array.
*/
function userCount() external view override returns (uint256) {
return state.users.length;
}
function lastRebalanceTimestamp() external view override returns (uint256) {
return state.lastRebalanceTimestamp;
}
}
contracts/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an manager) that can be granted exclusive access to
* specific functions.
*
* By default, the manager account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyManager`, which can be applied to your functions to restrict their use to
* the manager.
*/
contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _manager;
event OwnershipTransferred(address indexed previousManager, address indexed newManager);
/**
* @dev Initializes the contract setting the deployer as the initial manager.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the manager.
*/
modifier onlyManager() {
_checkManager();
_;
}
/**
* @dev Returns the address of the current manager.
*/
function manager() public view virtual returns (address) {
return _manager;
}
/**
* @dev Throws if the sender is not the manager.
*/
function _checkManager() internal view virtual {
require(manager() == _msgSender(), "Ownable: caller is not the manager");
}
/**
* @dev Leaves the contract without manager. It will not be possible to call
* `onlyManager` functions anymore. Can only be called by the current manager.
*
* NOTE: Renouncing ownership will leave the contract without a manager,
* thereby removing any functionality that is only available to the manager.
*/
function renounceOwnership() public virtual onlyManager {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newManager`).
* Can only be called by the current manager.
*/
function transferOwnership(address newManager) public virtual onlyManager {
require(newManager != address(0), "Ownable: new manager is the zero address");
_transferOwnership(newManager);
}
/**
* @dev Transfers ownership of the contract to a new account (`newManager`).
* Internal function without access restriction.
*/
function _transferOwnership(address newManager) internal virtual {
address oldManager = _manager;
_manager = newManager;
emit OwnershipTransferred(oldManager, newManager);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
contracts/errors/VaultErrors.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
library VaultErrors {
error MintNotStarted();
error NotAllowedToUpdateTicks();
error InvalidManagingFee();
error InvalidPerformanceFee();
error OnlyPoolAllowed();
error InvalidMintAmount();
error InvalidBurnAmount();
error MintNotAllowed();
error ZeroMintAmount();
error ZeroUnderlyingBalance();
error TicksOutOfRange();
error InvalidTicksSpacing();
error OnlyFactoryAllowed();
error LiquidityAlreadyAdded();
error ZeroManagerAddress();
error SlippageExceedThreshold();
error OnlyVaultAllowed();
error InsufficientNativeTokenAmount(uint256);
error RebalanceSlippageExceedsThreshold();
error ZeroRebalanceAmount();
error RebalanceIntervalNotReached();
error ZeroOtherFeeRecipientAddress();
}
contracts/interfaces/IRangeProtocolVault.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IPancakeV3MintCallback} from "../pancake/interfaces/callback/IPancakeV3MintCallback.sol";
import {IPancakeV3SwapCallback} from "../pancake/interfaces/callback/IPancakeV3SwapCallback.sol";
import {IPancakeV3Pool} from "../pancake/interfaces/IPancakeV3Pool.sol";
import {DataTypes} from "../libraries/DataTypes.sol";
interface IRangeProtocolVault is IERC20Upgradeable, IPancakeV3MintCallback, IPancakeV3SwapCallback {
// EVENTS
event Minted(
address indexed receiver,
uint256 mintAmount,
uint256 amount0In,
uint256 amount1In
);
event Burned(
address indexed receiver,
uint256 burnAmount,
uint256 amount0Out,
uint256 amount1Out
);
event LiquidityAdded(
uint256 liquidityMinted,
int24 tickLower,
int24 tickUpper,
uint256 amount0In,
uint256 amount1In
);
event LiquidityRemoved(
uint256 liquidityRemoved,
int24 tickLower,
int24 tickUpper,
uint256 amount0Out,
uint256 amount1Out
);
event FeesEarned(uint256 feesEarned0, uint256 feesEarned1);
event FeesUpdated(uint16 managingFee, uint16 performanceFee);
event InThePositionStatusSet(bool inThePosition);
event Swapped(bool zeroForOne, int256 amount0, int256 amount1);
event TicksSet(int24 lowerTick, int24 upperTick);
event MintStarted();
// GETTER FUNCTIONS
function lowerTick() external view returns (int24);
function upperTick() external view returns (int24);
function inThePosition() external view returns (bool);
function mintStarted() external view returns (bool);
function tickSpacing() external view returns (int24);
function pool() external view returns (IPancakeV3Pool);
function token0() external view returns (IERC20Upgradeable);
function token1() external view returns (IERC20Upgradeable);
function factory() external view returns (address);
function managingFee() external view returns (uint16);
function performanceFee() external view returns (uint16);
function managerBalance0() external view returns (uint256);
function managerBalance1() external view returns (uint256);
function userVaults(address user) external view returns (DataTypes.UserVault memory);
function users(uint256 index) external view returns (address);
function WETH9() external view returns (address);
function getUserVaults(
uint256 fromIdx,
uint256 toIdx
) external view returns (DataTypes.UserVaultInfo[] memory);
function getMintAmounts(
uint256 amount0Max,
uint256 amount1Max
) external view returns (uint256 amount0, uint256 amount1, uint256 mintAmount);
function getUnderlyingBalances()
external
view
returns (uint256 amount0Current, uint256 amount1Current);
function getCurrentFees() external view returns (uint256 fee0, uint256 fee1);
function getPositionID() external view returns (bytes32 positionID);
function userCount() external view returns (uint256);
function lastRebalanceTimestamp() external view returns (uint256);
// STATE MODIFYING FUNCTIONS
function initialize(address _pool, int24 _tickSpacing, bytes memory data) external;
function updateTicks(int24 _lowerTick, int24 _upperTick) external;
function mint(
uint256 mintAmount,
bool depositNative,
uint256[2] calldata maxAmountsIn
) external payable returns (uint256 amount0, uint256 amount1);
function burn(
uint256 burnAmount,
bool withdrawNative,
uint256[2] calldata minAmountsOut
) external returns (uint256 amount0, uint256 amount1);
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
function removeLiquidity(uint256[2] calldata minAmountsOut) external;
function swap(
bool zeroForOne,
int256 swapAmount,
uint160 sqrtPriceLimitX96,
uint256 minAmountOut
) external returns (int256 amount0, int256 amount1);
function addLiquidity(
int24 newLowerTick,
int24 newUpperTick,
uint256 amount0,
uint256 amount1,
uint256[2] calldata minAmountsIn,
uint256[2] calldata maxAmountsIn
) external returns (uint256 remainingAmount0, uint256 remainingAmount1);
function rebalance(
address target,
bytes calldata swapData,
bool zeroForOne,
uint256 amountIn
) external;
function mintETHx(uint256 amount) external returns (uint256 mintedETHx);
function pullFeeFromPool() external;
function collectManager() external;
function updateFees(uint16 newManagingFee, uint16 newPerformanceFee) external;
}
contracts/interfaces/IWETH9.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IWETH9 is IERC20Upgradeable {
function deposit() external payable;
function withdraw(uint) external;
}
contracts/interfaces/stader/IStaderConfig.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IStaderConfig {
// Errors
error InvalidLimits();
error InvalidMinDepositValue();
error InvalidMaxDepositValue();
error InvalidMinWithdrawValue();
error InvalidMaxWithdrawValue();
error IndenticalValue();
// Events
event SetConstant(bytes32 key, uint256 amount);
event SetVariable(bytes32 key, uint256 amount);
event SetAccount(bytes32 key, address newAddress);
event SetContract(bytes32 key, address newAddress);
event SetToken(bytes32 key, address newAddress);
//Contracts
function POOL_UTILS() external view returns (bytes32);
function POOL_SELECTOR() external view returns (bytes32);
function SD_COLLATERAL() external view returns (bytes32);
function OPERATOR_REWARD_COLLECTOR() external view returns (bytes32);
function VAULT_FACTORY() external view returns (bytes32);
function STADER_ORACLE() external view returns (bytes32);
function AUCTION_CONTRACT() external view returns (bytes32);
function PENALTY_CONTRACT() external view returns (bytes32);
function PERMISSIONED_POOL() external view returns (bytes32);
function STAKE_POOL_MANAGER() external view returns (bytes32);
function ETH_DEPOSIT_CONTRACT() external view returns (bytes32);
function PERMISSIONLESS_POOL() external view returns (bytes32);
function USER_WITHDRAW_MANAGER() external view returns (bytes32);
function STADER_INSURANCE_FUND() external view returns (bytes32);
function PERMISSIONED_NODE_REGISTRY() external view returns (bytes32);
function PERMISSIONLESS_NODE_REGISTRY() external view returns (bytes32);
function PERMISSIONED_SOCIALIZING_POOL() external view returns (bytes32);
function PERMISSIONLESS_SOCIALIZING_POOL() external view returns (bytes32);
function NODE_EL_REWARD_VAULT_IMPLEMENTATION() external view returns (bytes32);
function VALIDATOR_WITHDRAWAL_VAULT_IMPLEMENTATION() external view returns (bytes32);
//POR Feed Proxy
function ETH_BALANCE_POR_FEED() external view returns (bytes32);
function ETHX_SUPPLY_POR_FEED() external view returns (bytes32);
//Roles
function MANAGER() external view returns (bytes32);
function OPERATOR() external view returns (bytes32);
// Constants
function getStakedEthPerNode() external view returns (uint256);
function getPreDepositSize() external view returns (uint256);
function getFullDepositSize() external view returns (uint256);
function getDecimals() external view returns (uint256);
function getTotalFee() external view returns (uint256);
function getOperatorMaxNameLength() external view returns (uint256);
// Variables
function getSocializingPoolCycleDuration() external view returns (uint256);
function getSocializingPoolOptInCoolingPeriod() external view returns (uint256);
function getRewardsThreshold() external view returns (uint256);
function getMinDepositAmount() external view returns (uint256);
function getMaxDepositAmount() external view returns (uint256);
function getMinWithdrawAmount() external view returns (uint256);
function getMaxWithdrawAmount() external view returns (uint256);
function getMinBlockDelayToFinalizeWithdrawRequest() external view returns (uint256);
function getWithdrawnKeyBatchSize() external view returns (uint256);
// Accounts
function getAdmin() external view returns (address);
function getStaderTreasury() external view returns (address);
// Contracts
function getPoolUtils() external view returns (address);
function getPoolSelector() external view returns (address);
function getSDCollateral() external view returns (address);
function getOperatorRewardsCollector() external view returns (address);
function getVaultFactory() external view returns (address);
function getStaderOracle() external view returns (address);
function getAuctionContract() external view returns (address);
function getPenaltyContract() external view returns (address);
function getPermissionedPool() external view returns (address);
function getStakePoolManager() external view returns (address);
function getETHDepositContract() external view returns (address);
function getPermissionlessPool() external view returns (address);
function getUserWithdrawManager() external view returns (address);
function getStaderInsuranceFund() external view returns (address);
function getPermissionedNodeRegistry() external view returns (address);
function getPermissionlessNodeRegistry() external view returns (address);
function getPermissionedSocializingPool() external view returns (address);
function getPermissionlessSocializingPool() external view returns (address);
function getNodeELRewardVaultImplementation() external view returns (address);
function getValidatorWithdrawalVaultImplementation() external view returns (address);
function getETHBalancePORFeedProxy() external view returns (address);
function getETHXSupplyPORFeedProxy() external view returns (address);
// Tokens
function getStaderToken() external view returns (address);
function getETHxToken() external view returns (address);
//checks roles and stader contracts
function onlyStaderContract(address _addr, bytes32 _contractName) external view returns (bool);
function onlyManagerRole(address account) external view returns (bool);
function onlyOperatorRole(address account) external view returns (bool);
}
contracts/interfaces/stader/IStaderOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
/// @title ExchangeRate
/// @notice This struct holds data related to the exchange rate between ETH and ETHX.
struct ExchangeRate {
/// @notice The block number when the exchange rate was last updated.
uint256 reportingBlockNumber;
/// @notice The total balance of Ether (ETH) in the system.
uint256 totalETHBalance;
/// @notice The total supply of the liquid staking token (ETHX) in the system.
uint256 totalETHXSupply;
}
interface IStaderOracle {
function getExchangeRate() external view returns (ExchangeRate memory);
}
contracts/interfaces/stader/IStaderStakePoolManager.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IStaderStakePoolManager {
// Errors
error InvalidDepositAmount();
error UnsupportedOperation();
error InsufficientBalance();
error TransferFailed();
error PoolIdDoesNotExit();
error CooldownNotComplete();
error UnsupportedOperationInSafeMode();
// Events
event UpdatedStaderConfig(address staderConfig);
event Deposited(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
event ExecutionLayerRewardsReceived(uint256 amount);
event AuctionedEthReceived(uint256 amount);
event ReceivedExcessEthFromPool(uint8 indexed poolId);
event TransferredETHToUserWithdrawManager(uint256 amount);
event ETHTransferredToPool(uint256 indexed poolId, address poolAddress, uint256 validatorCount);
event WithdrawVaultUserShareReceived(uint256 amount);
event UpdatedExcessETHDepositCoolDown(uint256 excessETHDepositCoolDown);
function deposit(address _receiver) external payable returns (uint256);
function previewDeposit(uint256 _assets) external view returns (uint256);
function previewWithdraw(uint256 _shares) external view returns (uint256);
function getExchangeRate() external view returns (uint256);
function totalAssets() external view returns (uint256);
function convertToShares(uint256 _assets) external view returns (uint256);
function convertToAssets(uint256 _shares) external view returns (uint256);
function maxDeposit() external view returns (uint256);
function minDeposit() external view returns (uint256);
function receiveExecutionLayerRewards() external payable;
function receiveWithdrawVaultUserShare() external payable;
function receiveEthFromAuction() external payable;
function receiveExcessEthFromPool(uint8 _poolId) external payable;
function transferETHToUserWithdrawManager(uint256 _amount) external;
function validatorBatchDeposit(uint8 _poolId) external;
function depositETHOverTargetWeight() external;
function isVaultHealthy() external view returns (bool);
}
contracts/libraries/DataTypes.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IPancakeV3Pool} from "../pancake/interfaces/IPancakeV3Pool.sol";
library DataTypes {
struct UserVault {
bool exists;
uint256 token0;
uint256 token1;
}
struct UserVaultInfo {
address user;
uint256 token0;
uint256 token1;
}
struct State {
int24 lowerTick;
int24 upperTick;
bool inThePosition;
bool mintStarted;
int24 tickSpacing;
IPancakeV3Pool pool;
IERC20Upgradeable token0;
IERC20Upgradeable token1;
address factory;
uint16 managingFee;
uint16 performanceFee;
uint256 managerBalance0;
uint256 managerBalance1;
mapping(address => UserVault) userVaults;
address[] users;
address WETH9;
uint256 lastRebalanceTimestamp;
// NOTE: Only add more state variable below it and do not change the order of above state variables.
}
}
contracts/libraries/VaultLib.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {SafeCastUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol";
import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IERC20MetadataUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {IPancakeV3Pool} from "../pancake/interfaces/IPancakeV3Pool.sol";
import {IStaderConfig} from "../interfaces/stader/IStaderConfig.sol";
import {IStaderStakePoolManager} from "../interfaces/stader/IStaderStakePoolManager.sol";
import {IStaderOracle, ExchangeRate} from "../interfaces/stader/IStaderOracle.sol";
import {TickMath} from "../pancake/TickMath.sol";
import {LiquidityAmounts} from "../pancake/LiquidityAmounts.sol";
import {FullMath} from "../pancake/FullMath.sol";
import {IRangeProtocolVault} from "../interfaces/IRangeProtocolVault.sol";
import {VaultErrors} from "../errors/VaultErrors.sol";
import {IWETH9} from "../interfaces/IWETH9.sol";
import {DataTypes} from "../libraries/DataTypes.sol";
library VaultLib {
using SafeERC20Upgradeable for IERC20Upgradeable;
using TickMath for int24;
/// Performance fee cannot be set more than 20% of the fee earned from pancake v3 pool.
uint16 private constant MAX_PERFORMANCE_FEE_BPS = 2000;
/// Managing fee cannot be set more than 1% of the total fee earned.
uint16 private constant MAX_MANAGING_FEE_BPS = 100;
event Minted(
address indexed receiver,
uint256 mintAmount,
uint256 amount0In,
uint256 amount1In
);
event Burned(
address indexed receiver,
uint256 burnAmount,
uint256 amount0Out,
uint256 amount1Out
);
event LiquidityAdded(
uint256 liquidityMinted,
int24 tickLower,
int24 tickUpper,
uint256 amount0In,
uint256 amount1In
);
event LiquidityRemoved(
uint256 liquidityRemoved,
int24 tickLower,
int24 tickUpper,
uint256 amount0Out,
uint256 amount1Out
);
event FeesEarned(uint256 feesEarned0, uint256 feesEarned1);
event FeesUpdated(uint16 managingFee, uint16 performanceFee);
event InThePositionStatusSet(bool inThePosition);
event Swapped(bool zeroForOne, int256 amount0, int256 amount1);
event TicksSet(int24 lowerTick, int24 upperTick);
event MintStarted();
/**
* @notice updateTicks it is called by the contract manager to update the ticks.
* It can only be called once total supply is zero and the vault has not active position
* in the pancake pool
* @param _lowerTick lowerTick to set
* @param _upperTick upperTick to set
*/
function updateTicks(
DataTypes.State storage state,
int24 _lowerTick,
int24 _upperTick
) external {
if (IERC20Upgradeable(address(this)).totalSupply() != 0 || state.inThePosition)
revert VaultErrors.NotAllowedToUpdateTicks();
_updateTicks(state, _lowerTick, _upperTick);
if (!state.mintStarted) {
state.mintStarted = true;
emit MintStarted();
}
}
/// @notice pancakeV3MintCallback Pancake V3 callback fn, called back on pool.mint
function pancakeV3MintCallback(
DataTypes.State storage state,
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata
) external {
if (msg.sender != address(state.pool)) revert VaultErrors.OnlyPoolAllowed();
if (amount0Owed > 0) state.token0.safeTransfer(msg.sender, amount0Owed);
if (amount1Owed > 0) state.token1.safeTransfer(msg.sender, amount1Owed);
}
/// @notice pancakeV3SwapCallback Pancake v3 callback fn, called back on pool.swap
function pancakeV3SwapCallback(
DataTypes.State storage state,
int256 amount0Delta,
int256 amount1Delta,
bytes calldata
) external {
if (msg.sender != address(state.pool)) revert VaultErrors.OnlyPoolAllowed();
if (amount0Delta > 0) state.token0.safeTransfer(msg.sender, uint256(amount0Delta));
else if (amount1Delta > 0) state.token1.safeTransfer(msg.sender, uint256(amount1Delta));
}
struct MintLocalVars {
bool inThePosition;
uint256 totalSupply;
int24 lowerTick;
int24 upperTick;
IPancakeV3Pool pool;
}
/**
* @notice mint mints range vault shares, fractional shares of a Pancake V3 position/strategy
* to compute the amount of tokens necessary to mint `mintAmount` see getMintAmounts
* @param mintAmount The number of shares to mint
* @param maxAmountsIn max amounts to add in token0 and token1.
* @return amount0 amount of token0 transferred from msg.sender to mint `mintAmount`
* @return amount1 amount of token1 transferred from msg.sender to mint `mintAmount`
*/
function mint(
DataTypes.State storage state,
uint256 mintAmount,
bool depositNative,
uint256[2] calldata maxAmountsIn
) external returns (uint256 amount0, uint256 amount1) {
if (!state.mintStarted) revert VaultErrors.MintNotStarted();
if (mintAmount == 0) revert VaultErrors.InvalidMintAmount();
IRangeProtocolVault vault = IRangeProtocolVault(address(this));
MintLocalVars memory vars;
(vars.inThePosition, vars.totalSupply, vars.lowerTick, vars.upperTick, vars.pool) = (
state.inThePosition,
vault.totalSupply(),
state.lowerTick,
state.upperTick,
state.pool
);
(uint160 sqrtRatioX96, , , , , , ) = vars.pool.slot0();
if (vars.totalSupply > 0) {
(uint256 amount0Current, uint256 amount1Current) = getUnderlyingBalances(state);
amount0 = FullMath.mulDivRoundingUp(amount0Current, mintAmount, vars.totalSupply);
amount1 = FullMath.mulDivRoundingUp(amount1Current, mintAmount, vars.totalSupply);
} else if (vars.inThePosition) {
// If total supply is zero then inThePosition must be set to accept token0 and token1 based on currently set ticks.
// This branch will be executed for the first mint and as well as each time total supply is to be changed from zero to non-zero.
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
vars.lowerTick.getSqrtRatioAtTick(),
vars.upperTick.getSqrtRatioAtTick(),
SafeCastUpgradeable.toUint128(mintAmount)
);
} else {
// If total supply is zero and the vault is not in the position then mint cannot be accepted based on the assumptions
// that being out of the pool renders currently set ticks unusable and totalSupply being zero does not allow
// calculating correct amounts of amount0 and amount1 to be accepted from the user.
// This branch will be executed if all users remove their liquidity from the vault i.e. total supply is zero from non-zero and
// the vault is out of the position i.e. no valid tick range to calculate the vault's mint shares.
// Manager must call initialize function with valid tick ranges to enable the minting again.
revert VaultErrors.MintNotAllowed();
}
if (amount0 > maxAmountsIn[0] || amount1 > maxAmountsIn[1])
revert VaultErrors.SlippageExceedThreshold();
vault.mint(msg.sender, mintAmount);
_processDeposit(state, depositNative, amount0, amount1);
if (vars.inThePosition) {
uint128 liquidityMinted = LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
vars.lowerTick.getSqrtRatioAtTick(),
vars.upperTick.getSqrtRatioAtTick(),
amount0,
amount1
);
vars.pool.mint(address(this), vars.lowerTick, vars.upperTick, liquidityMinted, "");
}
emit Minted(msg.sender, mintAmount, amount0, amount1);
if (address(this).balance != 0) msg.sender.call{value: address(this).balance}("");
}
function _processDeposit(
DataTypes.State storage state,
bool depositNative,
uint256 amount0,
uint256 amount1
) private {
DataTypes.UserVault storage userVault = state.userVaults[msg.sender];
IWETH9 WETH9 = IWETH9(state.WETH9);
IERC20Upgradeable token0 = state.token0;
IERC20Upgradeable token1 = state.token1;
userVault.token0 += amount0;
userVault.token1 += amount1;
if (!userVault.exists) {
userVault.exists = true;
state.users.push(msg.sender);
}
(bool isToken0Native, bool isToken1Native) = (
address(token0) == address(WETH9),
address(token1) == address(WETH9)
);
if (amount0 != 0) {
if (isToken0Native && depositNative) {
if (msg.value < amount0) {
revert VaultErrors.InsufficientNativeTokenAmount(msg.value);
}
WETH9.deposit{value: amount0}();
} else {
token0.safeTransferFrom(msg.sender, address(this), amount0);
}
}
if (amount1 != 0) {
if (isToken1Native && depositNative) {
if (msg.value < amount1) {
revert VaultErrors.InsufficientNativeTokenAmount(msg.value);
}
WETH9.deposit{value: amount1}();
} else {
token1.safeTransferFrom(msg.sender, address(this), amount1);
}
}
}
struct BurnLocalVars {
uint256 totalSupply;
IERC20Upgradeable token0;
IERC20Upgradeable token1;
uint256 feeBalance0;
uint256 feeBalance1;
uint256 passiveBalance0;
uint256 passiveBalance1;
uint256 balanceBefore;
}
/**
* @notice burn burns range vault shares (shares of a Pancake V3 position) and receive underlying
* @param burnAmount The number of shares to burn
* @param withdrawNative to withdraw in Native tokens or not
* @param minAmountsOut min token amounts out
* @return amount0 amount of token0 transferred to msg.sender for burning {burnAmount}
* @return amount1 amount of token1 transferred to msg.sender for burning {burnAmount}
*/
function burn(
DataTypes.State storage state,
uint256 burnAmount,
bool withdrawNative,
uint256[2] calldata minAmountsOut
) external returns (uint256 amount0, uint256 amount1) {
if (burnAmount == 0) revert VaultErrors.InvalidBurnAmount();
IRangeProtocolVault vault = IRangeProtocolVault(address(this));
BurnLocalVars memory vars;
(
vars.totalSupply,
vars.token0,
vars.token1,
vars.feeBalance0,
vars.feeBalance1,
vars.balanceBefore
) = (
vault.totalSupply(),
state.token0,
state.token1,
state.managerBalance0,
state.managerBalance1,
vault.balanceOf(msg.sender)
);
if (state.inThePosition) {
(uint128 liquidity, , , , ) = state.pool.positions(getPositionID(state));
uint256 liquidityBurned_ = FullMath.mulDiv(burnAmount, liquidity, vars.totalSupply);
uint128 liquidityBurned = SafeCastUpgradeable.toUint128(liquidityBurned_);
(uint256 burn0, uint256 burn1, uint256 fee0, uint256 fee1) = _withdraw(
state,
liquidityBurned
);
_applyPerformanceFee(state, fee0, fee1);
(fee0, fee1) = _netPerformanceFees(state, fee0, fee1);
emit FeesEarned(fee0, fee1);
vars.passiveBalance0 = vars.token0.balanceOf(address(this)) - burn0;
vars.passiveBalance1 = vars.token1.balanceOf(address(this)) - burn1;
if (vars.passiveBalance0 > vars.feeBalance0) vars.passiveBalance0 -= vars.feeBalance0;
if (vars.passiveBalance1 > vars.feeBalance1) vars.passiveBalance1 -= vars.feeBalance1;
amount0 = burn0 + FullMath.mulDiv(vars.passiveBalance0, burnAmount, vars.totalSupply);
amount1 = burn1 + FullMath.mulDiv(vars.passiveBalance1, burnAmount, vars.totalSupply);
} else {
(uint256 amount0Current, uint256 amount1Current) = getUnderlyingBalances(state);
amount0 = FullMath.mulDiv(amount0Current, burnAmount, vars.totalSupply);
amount1 = FullMath.mulDiv(amount1Current, burnAmount, vars.totalSupply);
}
if (amount0 < minAmountsOut[0] || amount1 < minAmountsOut[1])
revert VaultErrors.SlippageExceedThreshold();
vault.burn(msg.sender, burnAmount);
_applyManagingFee(state, amount0, amount1);
(amount0, amount1) = _netManagingFees(state, amount0, amount1);
_processWithdraw(
state,
vars.balanceBefore,
vars.balanceBefore - burnAmount,
withdrawNative,
amount0,
amount1
);
emit Burned(msg.sender, burnAmount, amount0, amount1);
}
function _processWithdraw(
DataTypes.State storage state,
uint256 balanceBefore,
uint256 balanceAfter,
bool withdrawNative,
uint256 amount0,
uint256 amount1
) private {
DataTypes.UserVault storage userVault = state.userVaults[msg.sender];
IWETH9 WETH9 = IWETH9(state.WETH9);
IERC20Upgradeable token0 = state.token0;
IERC20Upgradeable token1 = state.token1;
userVault.token0 = (userVault.token0 * balanceAfter) / balanceBefore;
userVault.token1 = (userVault.token1 * balanceAfter) / balanceBefore;
(bool isToken0Native, bool isToken1Native) = (
address(token0) == address(WETH9),
address(token1) == address(WETH9)
);
uint256 weth9Amount = 0;
if (amount0 != 0) {
if (isToken0Native && withdrawNative) {
weth9Amount = amount0;
} else {
token0.safeTransfer(msg.sender, amount0);
}
}
if (amount1 != 0) {
if (isToken1Native && withdrawNative) {
weth9Amount = amount1;
} else {
token1.safeTransfer(msg.sender, amount1);
}
}
if (weth9Amount != 0) {
WETH9.withdraw(amount0);
msg.sender.call{value: weth9Amount}("");
}
}
/**
* @notice removeLiquidity removes liquidity from pancake pool and receives underlying tokens
* in the vault contract.
* @param minAmountsOut minimum amounts to get from the pool upon removal of liquidity.
*/
function removeLiquidity(
DataTypes.State storage state,
uint256[2] calldata minAmountsOut
) external {
(uint128 liquidity, , , , ) = state.pool.positions(getPositionID(state));
if (liquidity > 0) {
int24 _lowerTick = state.lowerTick;
int24 _upperTick = state.upperTick;
(uint256 amount0, uint256 amount1, uint256 fee0, uint256 fee1) = _withdraw(
state,
liquidity
);
if (amount0 < minAmountsOut[0] || amount1 < minAmountsOut[1])
revert VaultErrors.SlippageExceedThreshold();
emit LiquidityRemoved(liquidity, _lowerTick, _upperTick, amount0, amount1);
_applyPerformanceFee(state, fee0, fee1);
(fee0, fee1) = _netPerformanceFees(state, fee0, fee1);
emit FeesEarned(fee0, fee1);
}
// TicksSet event is not emitted here since the emitting would create a new position on subgraph but
// the following statement is to only disallow any liquidity provision through the vault unless done
// by manager (taking into account any features added in future).
state.lowerTick = state.upperTick;
state.inThePosition = false;
emit InThePositionStatusSet(false);
}
/**
* @dev Mars@RangeProtocol
* @notice swap swaps token0 for token1 (token0 in, token1 out), or token1 for token0 (token1 in token0 out).
* Zero for one will cause the price: amount1 / amount0 lower, otherwise it will cause the price higher
* @param zeroForOne The direction of the swap, true is swap token0 for token1, false is swap token1 to token0
* @param swapAmount The exact input token amount of the swap
* @param sqrtPriceLimitX96 threshold price ratio after the swap.
* If zero for one, the price cannot be lower (swap make price lower) than this threshold value after the swap
* If one for zero, the price cannot be greater (swap make price higher) than this threshold value after the swap
* @param minAmountOut minimum amount to protect against slippage.
* @return amount0 If positive represents exact input token0 amount after this swap, msg.sender paid amount,
* or exact output token0 amount (negative), msg.sender received amount
* @return amount1 If positive represents exact input token1 amount after this swap, msg.sender paid amount,
* or exact output token1 amount (negative), msg.sender received amount
*/
function swap(
DataTypes.State storage state,
bool zeroForOne,
int256 swapAmount,
uint160 sqrtPriceLimitX96,
uint256 minAmountOut
) external returns (int256 amount0, int256 amount1) {
(amount0, amount1) = state.pool.swap(
address(this),
zeroForOne,
swapAmount,
sqrtPriceLimitX96,
""
);
if (
(zeroForOne && uint256(-amount1) < minAmountOut) ||
(!zeroForOne && uint256(-amount0) < minAmountOut)
) revert VaultErrors.SlippageExceedThreshold();
emit Swapped(zeroForOne, amount0, amount1);
}
/**
* @dev Mars@RangeProtocol
* @notice addLiquidity allows manager to add liquidity into pancake pool into newer tick ranges.
* @param newLowerTick new lower tick to deposit liquidity into
* @param newUpperTick new upper tick to deposit liquidity into
* @param amount0 max amount of amount0 to use
* @param amount1 max amount of amount1 to use
* @param minAmountsIn minimum amounts to add for slippage protection
* @param maxAmountsIn minimum amounts to add for slippage protection
* @return remainingAmount0 remaining amount from amount0
* @return remainingAmount1 remaining amount from amount1
*/
function addLiquidity(
DataTypes.State storage state,
int24 newLowerTick,
int24 newUpperTick,
uint256 amount0,
uint256 amount1,
uint256[2] calldata minAmountsIn,
uint256[2] calldata maxAmountsIn
) external returns (uint256 remainingAmount0, uint256 remainingAmount1) {
if (state.inThePosition) revert VaultErrors.LiquidityAlreadyAdded();
(uint160 sqrtRatioX96, , , , , , ) = state.pool.slot0();
uint128 baseLiquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
newLowerTick.getSqrtRatioAtTick(),
newUpperTick.getSqrtRatioAtTick(),
amount0,
amount1
);
if (baseLiquidity > 0) {
(uint256 amountDeposited0, uint256 amountDeposited1) = state.pool.mint(
address(this),
newLowerTick,
newUpperTick,
baseLiquidity,
""
);
if (
amountDeposited0 < minAmountsIn[0] ||
amountDeposited0 > maxAmountsIn[0] ||
amountDeposited1 < minAmountsIn[1] ||
amountDeposited1 > maxAmountsIn[1]
) revert VaultErrors.SlippageExceedThreshold();
_updateTicks(state, newLowerTick, newUpperTick);
emit LiquidityAdded(
baseLiquidity,
newLowerTick,
newUpperTick,
amountDeposited0,
amountDeposited1
);
// Should return remaining token number for swap
remainingAmount0 = amount0 - amountDeposited0;
remainingAmount1 = amount1 - amountDeposited1;
}
}
struct RebalanceLocalVars {
uint256 balance0Before;
uint256 balance1Before;
uint256 balance0After;
uint256 balance1After;
uint256 amount0Delta;
uint256 amount1Delta;
}
/*
* @dev Allows rebalance of the vault by manager using off-chain quote and non-pool venues.
* @param target address of the target swap venue.
* @param swapData data to send to the target swap venue.
* @param zeroForOne swap direction, true for x -> y; false for y -> x.
* @param amountIn amount of tokenIn to swap.
**/
function rebalance(
DataTypes.State storage state,
address staderOracle,
address target,
bytes calldata swapData,
bool zeroForOne,
uint256 amountIn
) external {
if (state.lastRebalanceTimestamp + 15 minutes > block.timestamp)
revert VaultErrors.RebalanceIntervalNotReached();
state.lastRebalanceTimestamp = block.timestamp;
if (amountIn == 0) revert VaultErrors.ZeroRebalanceAmount();
IERC20MetadataUpgradeable token0 = IERC20MetadataUpgradeable(address(state.token0));
IERC20MetadataUpgradeable token1 = IERC20MetadataUpgradeable(address(state.token1));
RebalanceLocalVars memory vars;
vars.balance0Before = token0.balanceOf(address(this));
vars.balance1Before = token1.balanceOf(address(this));
// perform the rebalance call.
IERC20Upgradeable tokenIn = zeroForOne
? IERC20Upgradeable(address(token0))
: IERC20Upgradeable(address(token1));
tokenIn.safeApprove(target, amountIn);
Address.functionCall(target, swapData);
tokenIn.safeApprove(target, 0);
vars.balance0After = token0.balanceOf(address(this));
vars.balance1After = token1.balanceOf(address(this));
vars.amount0Delta = vars.balance0After > vars.balance0Before
? vars.balance0After - vars.balance0Before
: vars.balance0Before - vars.balance0After;
vars.amount1Delta = vars.balance1After > vars.balance1Before
? vars.balance1After - vars.balance1Before
: vars.balance1Before - vars.balance1After;
uint256 swapPrice = (vars.amount1Delta * 10 ** token0.decimals()) / vars.amount0Delta;
ExchangeRate memory er = IStaderOracle(staderOracle).getExchangeRate();
uint256 priceFromOracle = (er.totalETHBalance * 10 ** 18) / er.totalETHXSupply;
uint256 swapRatio = (priceFromOracle * 10_000) / swapPrice;
if (swapRatio < 9900 || swapRatio > 10100) {
revert VaultErrors.RebalanceSlippageExceedsThreshold();
}
}
function mintETHx(
DataTypes.State storage state,
address staderConfig,
uint256 amount
) external returns (uint256 mintedETHx) {
if (amount == 0) revert();
IWETH9(state.WETH9).withdraw(amount);
mintedETHx = IStaderStakePoolManager(IStaderConfig(staderConfig).getStakePoolManager())
.deposit{value: amount}(address(this));
}
/**
* @dev pullFeeFromPool pulls accrued fee from pancake v3 pool that position has accrued since
* last collection.
*/
function pullFeeFromPool(DataTypes.State storage state) external {
_pullFeeFromPool(state);
}
/// @notice collectManager collects manager fees accrued
function collectManager(DataTypes.State storage state, address manager) external {
uint256 amount0 = state.managerBalance0;
uint256 amount1 = state.managerBalance1;
state.managerBalance0 = 0;
state.managerBalance1 = 0;
if (amount0 > 0) {
state.token0.safeTransfer(manager, amount0);
}
if (amount1 > 0) {
state.token1.safeTransfer(manager, amount1);
}
}
/**
* @notice updateFees allows updating of managing and performance fees
*/
function updateFees(
DataTypes.State storage state,
uint16 newManagingFee,
uint16 newPerformanceFee
) external {
_updateFees(state, newManagingFee, newPerformanceFee);
}
/**
* @notice compute maximum shares that can be minted from `amount0Max` and `amount1Max`
* @param amount0Max The maximum amount of token0 to forward on mint
* @param amount1Max The maximum amount of token1 to forward on mint
* @return amount0 actual amount of token0 to forward when minting `mintAmount`
* @return amount1 actual amount of token1 to forward when minting `mintAmount`
* @return mintAmount maximum number of shares mintable
*/
function getMintAmounts(
DataTypes.State storage state,
uint256 amount0Max,
uint256 amount1Max
) external view returns (uint256 amount0, uint256 amount1, uint256 mintAmount) {
if (!state.mintStarted) revert VaultErrors.MintNotStarted();
uint256 totalSupply = IRangeProtocolVault(address(this)).totalSupply();
if (totalSupply > 0) {
(amount0, amount1, mintAmount) = _calcMintAmounts(
state,
totalSupply,
amount0Max,
amount1Max
);
} else if (state.inThePosition) {
(uint160 sqrtRatioX96, , , , , , ) = state.pool.slot0();
(int24 lowerTick, int24 upperTick) = (state.lowerTick, state.upperTick);
uint128 newLiquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
amount0Max,
amount1Max
);
mintAmount = uint256(newLiquidity);
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
newLiquidity
);
}
}
/**
* @notice getCurrentFees returns the current uncollected fees
* @return fee0 uncollected fee in token0
* @return fee1 uncollected fee in token1
*/
function getCurrentFees(
DataTypes.State storage state
) external view returns (uint256 fee0, uint256 fee1) {
(, int24 tick, , , , , ) = state.pool.slot0();
(
uint128 liquidity,
uint256 feeGrowthInside0Last,
uint256 feeGrowthInside1Last,
uint128 tokensOwed0,
uint128 tokensOwed1
) = state.pool.positions(getPositionID(state));
fee0 =
_feesEarned(state, true, feeGrowthInside0Last, tick, liquidity) +
uint256(tokensOwed0);
fee1 =
_feesEarned(state, false, feeGrowthInside1Last, tick, liquidity) +
uint256(tokensOwed1);
(fee0, fee1) = _netPerformanceFees(state, fee0, fee1);
}
/**
* @notice getPositionID returns the position id of the vault in pancake pool
* @return positionID position id of the vault in pancake pool
*/
function getPositionID(DataTypes.State storage state) public view returns (bytes32 positionID) {
return keccak256(abi.encodePacked(address(this), state.lowerTick, state.upperTick));
}
/**
* @notice compute total underlying token0 and token1 token supply at current price
* includes current liquidity invested in pancake position, current fees earned
* and any uninvested leftover (but does not include manager fees accrued)
* @return amount0Current current total underlying balance of token0
* @return amount1Current current total underlying balance of token1
*/
function getUnderlyingBalances(
DataTypes.State storage state
) public view returns (uint256 amount0Current, uint256 amount1Current) {
(uint160 sqrtRatioX96, int24 tick, , , , , ) = state.pool.slot0();
return _getUnderlyingBalances(state, sqrtRatioX96, tick);
}
function getUnderlyingBalancesByShare(
DataTypes.State storage state,
uint256 shares
) external view returns (uint256 amount0, uint256 amount1) {
uint256 _totalSupply = IRangeProtocolVault(address(this)).totalSupply();
if (_totalSupply != 0) {
// getUnderlyingBalances already applies performanceFee
(uint256 amount0Current, uint256 amount1Current) = getUnderlyingBalances(state);
amount0 = (shares * amount0Current) / _totalSupply;
amount1 = (shares * amount1Current) / _totalSupply;
// apply managing fee
(amount0, amount1) = _netManagingFees(state, amount0, amount1);
}
}
struct UnderlyingBalanceLocalVars {
uint256 passiveBalance0;
uint256 passiveBalance1;
uint256 feeBalance0;
uint256 feeBalance1;
}
/**
* @notice _getUnderlyingBalances internal function to calculate underlying balances
* @param sqrtRatioX96 price to calculate underlying balances at
* @param tick tick at the given price
* @return amount0Current current amount of token0
* @return amount1Current current amount of token1
*/
function _getUnderlyingBalances(
DataTypes.State storage state,
uint160 sqrtRatioX96,
int24 tick
) internal view returns (uint256 amount0Current, uint256 amount1Current) {
(
uint128 liquidity,
uint256 feeGrowthInside0Last,
uint256 feeGrowthInside1Last,
uint128 tokensOwed0,
uint128 tokensOwed1
) = state.pool.positions(getPositionID(state));
uint256 fee0;
uint256 fee1;
if (liquidity != 0) {
(amount0Current, amount1Current) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
state.lowerTick.getSqrtRatioAtTick(),
state.upperTick.getSqrtRatioAtTick(),
liquidity
);
fee0 =
_feesEarned(state, true, feeGrowthInside0Last, tick, liquidity) +
uint256(tokensOwed0);
fee1 =
_feesEarned(state, false, feeGrowthInside1Last, tick, liquidity) +
uint256(tokensOwed1);
(fee0, fee1) = _netPerformanceFees(state, fee0, fee1);
amount0Current += fee0;
amount1Current += fee1;
}
UnderlyingBalanceLocalVars memory vars;
vars.passiveBalance0 = state.token0.balanceOf(address(this));
vars.passiveBalance1 = state.token1.balanceOf(address(this));
vars.feeBalance0 = state.managerBalance0;
vars.feeBalance1 = state.managerBalance1;
amount0Current += vars.passiveBalance0 > vars.feeBalance0
? vars.passiveBalance0 - vars.feeBalance0
: vars.passiveBalance0;
amount1Current += vars.passiveBalance1 > vars.feeBalance1
? vars.passiveBalance1 - vars.feeBalance1
: vars.passiveBalance1;
}
/**
* @notice The userVault mapping is updated before the vault share tokens are transferred between the users.
* The data from this mapping is used by off-chain strategy manager. The data in this mapping does not impact
* the on-chain behaviour of vault or users' funds.
* @dev transfers userVault amounts based on the transferring user vault shares
* @param from address to transfer userVault amount from
* @param to address to transfer userVault amount to
*/
function _beforeTokenTransfer(
DataTypes.State storage state,
address from,
address to,
uint256 amount
) external {
// for mint and burn the user vaults adjustment are handled in the respective functions
if (from == address(0x0) || to == address(0x0)) return;
if (!state.userVaults[to].exists) {
state.userVaults[to].exists = true;
state.users.push(to);
}
uint256 senderBalanceBefore = IERC20Upgradeable(address(this)).balanceOf(from);
uint256 senderBalanceAfter = senderBalanceBefore - amount;
uint256 token0Amount = state.userVaults[from].token0 -
(state.userVaults[from].token0 * senderBalanceAfter) /
senderBalanceBefore;
uint256 token1Amount = state.userVaults[from].token1 -
(state.userVaults[from].token1 * senderBalanceAfter) /
senderBalanceBefore;
state.userVaults[from].token0 -= token0Amount;
state.userVaults[from].token1 -= token1Amount;
state.userVaults[to].token0 += token0Amount;
state.userVaults[to].token1 += token1Amount;
}
/**
* @notice _withdraw internal function to withdraw liquidity from uniswap pool
* @param liquidity liquidity to remove from the uniswap pool
*/
function _withdraw(
DataTypes.State storage state,
uint128 liquidity
) private returns (uint256 burn0, uint256 burn1, uint256 fee0, uint256 fee1) {
int24 _lowerTick = state.lowerTick;
int24 _upperTick = state.upperTick;
uint256 preBalance0 = state.token0.balanceOf(address(this));
uint256 preBalance1 = state.token1.balanceOf(address(this));
(burn0, burn1) = state.pool.burn(_lowerTick, _upperTick, liquidity);
state.pool.collect(
address(this),
_lowerTick,
_upperTick,
type(uint128).max,
type(uint128).max
);
fee0 = state.token0.balanceOf(address(this)) - preBalance0 - burn0;
fee1 = state.token1.balanceOf(address(this)) - preBalance1 - burn1;
}
/**
* @notice _calcMintAmounts internal function to calculate the amount based on the max supply of token0 and token1
* and current supply of RangeVault shares.
* @param totalSupply current total supply of range vault shares
* @param amount0Max max amount of token0 to compute mint amount
* @param amount1Max max amount of token1 to compute mint amount
*/
function _calcMintAmounts(
DataTypes.State storage state,
uint256 totalSupply,
uint256 amount0Max,
uint256 amount1Max
) private view returns (uint256 amount0, uint256 amount1, uint256 mintAmount) {
(uint256 amount0Current, uint256 amount1Current) = getUnderlyingBalances(state);
if (amount0Current == 0 && amount1Current > 0) {
mintAmount = FullMath.mulDiv(amount1Max, totalSupply, amount1Current);
} else if (amount1Current == 0 && amount0Current > 0) {
mintAmount = FullMath.mulDiv(amount0Max, totalSupply, amount0Current);
} else if (amount0Current == 0 && amount1Current == 0) {
revert VaultErrors.ZeroUnderlyingBalance();
} else {
uint256 amount0Mint = FullMath.mulDiv(amount0Max, totalSupply, amount0Current);
uint256 amount1Mint = FullMath.mulDiv(amount1Max, totalSupply, amount1Current);
if (amount0Mint == 0 || amount1Mint == 0) revert VaultErrors.ZeroMintAmount();
mintAmount = amount0Mint < amount1Mint ? amount0Mint : amount1Mint;
}
amount0 = FullMath.mulDivRoundingUp(mintAmount, amount0Current, totalSupply);
amount1 = FullMath.mulDivRoundingUp(mintAmount, amount1Current, totalSupply);
}
/**
* @notice _feesEarned internal function to return the fees accrued
* @param isZero true to compute fee for token0 and false to compute fee for token1
* @param feeGrowthInsideLast last time the fee was realized for the vault in pancake pool
*/
function _feesEarned(
DataTypes.State storage state,
bool isZero,
uint256 feeGrowthInsideLast,
int24 tick,
uint128 liquidity
) private view returns (uint256 fee) {
uint256 feeGrowthOutsideLower;
uint256 feeGrowthOutsideUpper;
uint256 feeGrowthGlobal;
(IPancakeV3Pool pool, int24 lowerTick, int24 upperTick) = (
state.pool,
state.lowerTick,
state.upperTick
);
if (isZero) {
feeGrowthGlobal = pool.feeGrowthGlobal0X128();
(, , feeGrowthOutsideLower, , , , , ) = pool.ticks(lowerTick);
(, , feeGrowthOutsideUpper, , , , , ) = pool.ticks(upperTick);
} else {
feeGrowthGlobal = pool.feeGrowthGlobal1X128();
(, , , feeGrowthOutsideLower, , , , ) = pool.ticks(lowerTick);
(, , , feeGrowthOutsideUpper, , , , ) = pool.ticks(upperTick);
}
unchecked {
uint256 feeGrowthBelow;
if (tick >= lowerTick) {
feeGrowthBelow = feeGrowthOutsideLower;
} else {
feeGrowthBelow = feeGrowthGlobal - feeGrowthOutsideLower;
}
uint256 feeGrowthAbove;
if (tick < upperTick) {
feeGrowthAbove = feeGrowthOutsideUpper;
} else {
feeGrowthAbove = feeGrowthGlobal - feeGrowthOutsideUpper;
}
uint256 feeGrowthInside = feeGrowthGlobal - feeGrowthBelow - feeGrowthAbove;
fee = FullMath.mulDiv(
liquidity,
feeGrowthInside - feeGrowthInsideLast,
0x100000000000000000000000000000000
);
}
}
/**
* @notice _applyManagingFee applies the managing fee to the notional value of the redeeming user.
* @param amount0 user's notional value in token0
* @param amount1 user's notional value in token1
*/
function _applyManagingFee(
DataTypes.State storage state,
uint256 amount0,
uint256 amount1
) private {
uint256 _managingFee = state.managingFee;
state.managerBalance0 += (amount0 * _managingFee) / 10_000;
state.managerBalance1 += (amount1 * _managingFee) / 10_000;
}
/**
* @notice _applyPerformanceFee applies the performance fee to the fees earned from pancake v3 pool.
* @param fee0 fee earned in token0
* @param fee1 fee earned in token1
*/
function _applyPerformanceFee(
DataTypes.State storage state,
uint256 fee0,
uint256 fee1
) private {
uint256 _performanceFee = state.performanceFee;
state.managerBalance0 += (fee0 * _performanceFee) / 10_000;
state.managerBalance1 += (fee1 * _performanceFee) / 10_000;
}
/**
* @notice _netManagingFees computes the fee share for manager from notional value of the redeeming user.
* @param amount0 user's notional value in token0
* @param amount1 user's notional value in token1
* @return amount0AfterFee user's notional value in token0 after managing fee deduction
* @return amount1AfterFee user's notional value in token1 after managing fee deduction
*/
function _netManagingFees(
DataTypes.State storage state,
uint256 amount0,
uint256 amount1
) private view returns (uint256 amount0AfterFee, uint256 amount1AfterFee) {
uint256 _managingFee = state.managingFee;
uint256 deduct0 = (amount0 * _managingFee) / 10_000;
uint256 deduct1 = (amount1 * _managingFee) / 10_000;
amount0AfterFee = amount0 - deduct0;
amount1AfterFee = amount1 - deduct1;
}
/**
* @notice _netPerformanceFees computes the fee share for manager as performance fee from the fee earned from pancake v3 pool.
* @param rawFee0 fee earned in token0 from pancake v3 pool.
* @param rawFee1 fee earned in token1 from pancake v3 pool.
* @return fee0AfterDeduction fee in token0 earned after deducting performance fee from earned fee.
* @return fee1AfterDeduction fee in token1 earned after deducting performance fee from earned fee.
*/
function _netPerformanceFees(
DataTypes.State storage state,
uint256 rawFee0,
uint256 rawFee1
) private view returns (uint256 fee0AfterDeduction, uint256 fee1AfterDeduction) {
uint256 _performanceFee = state.performanceFee;
uint256 deduct0 = ((rawFee0 * _performanceFee) / 10_000);
uint256 deduct1 = ((rawFee1 * _performanceFee) / 10_000);
fee0AfterDeduction = rawFee0 - deduct0;
fee1AfterDeduction = rawFee1 - deduct1;
}
/**
* @notice _updateTicks internal function to validate and update ticks
* _lowerTick lower tick to update
* _upperTick upper tick to update
*/
function _updateTicks(
DataTypes.State storage state,
int24 _lowerTick,
int24 _upperTick
) private {
_validateTicks(state, _lowerTick, _upperTick);
state.lowerTick = _lowerTick;
state.upperTick = _upperTick;
// Upon updating ticks inThePosition status is set to true.
state.inThePosition = true;
emit InThePositionStatusSet(true);
emit TicksSet(_lowerTick, _upperTick);
}
/**
* @notice _validateTicks validates the upper and lower ticks
* @param _lowerTick lower tick to validate
* @param _upperTick upper tick to validate
*/
function _validateTicks(
DataTypes.State storage state,
int24 _lowerTick,
int24 _upperTick
) private view {
if (_lowerTick < TickMath.MIN_TICK || _upperTick > TickMath.MAX_TICK)
revert VaultErrors.TicksOutOfRange();
if (
_lowerTick >= _upperTick ||
_lowerTick % state.tickSpacing != 0 ||
_upperTick % state.tickSpacing != 0
) revert VaultErrors.InvalidTicksSpacing();
}
/**
* @notice internal function that pulls fee from the pool
*/
function _pullFeeFromPool(DataTypes.State storage state) private {
(, , uint256 fee0, uint256 fee1) = _withdraw(state, 0);
_applyPerformanceFee(state, fee0, fee1);
(fee0, fee1) = _netPerformanceFees(state, fee0, fee1);
emit FeesEarned(fee0, fee1);
}
/**
* @notice internal function that updates the fee percentages for both performance
* and managing fee.
* @param newManagingFee new managing fee to set.
* @param newPerformanceFee new performance fee to set.
*/
function _updateFees(
DataTypes.State storage state,
uint16 newManagingFee,
uint16 newPerformanceFee
) private {
if (newManagingFee > MAX_MANAGING_FEE_BPS) revert VaultErrors.InvalidManagingFee();
if (newPerformanceFee > MAX_PERFORMANCE_FEE_BPS) revert VaultErrors.InvalidPerformanceFee();
if (state.inThePosition) _pullFeeFromPool(state);
state.managingFee = newManagingFee;
state.performanceFee = newPerformanceFee;
emit FeesUpdated(newManagingFee, newPerformanceFee);
}
}
contracts/pancake/FixedPoint96.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.4;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
contracts/pancake/FullMath.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
// EDIT for 0.8 compatibility:
// see: https://ethereum.stackexchange.com/questions/96642/unary-operator-cannot-be-applied-to-type-uint256
uint256 twos = denominator & (~denominator + 1);
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
contracts/pancake/LiquidityAmounts.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import {FullMath} from "./FullMath.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate =
FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return
toUint128(
FullMath.mulDiv(
amount0,
intermediate,
sqrtRatioBX96 - sqrtRatioAX96
)
);
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
toUint128(
FullMath.mulDiv(
amount1,
FixedPoint96.Q96,
sqrtRatioBX96 - sqrtRatioAX96
)
);
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(
sqrtRatioAX96,
sqrtRatioBX96,
amount0
);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 =
getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 =
getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(
sqrtRatioAX96,
sqrtRatioBX96,
amount1
);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The liquidity being valued
/// @return amount0 The amount0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The liquidity being valued
/// @return amount1 The amount1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
liquidity,
sqrtRatioBX96 - sqrtRatioAX96,
FixedPoint96.Q96
);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(
sqrtRatioAX96,
sqrtRatioBX96,
liquidity
);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(
sqrtRatioX96,
sqrtRatioBX96,
liquidity
);
amount1 = getAmount1ForLiquidity(
sqrtRatioAX96,
sqrtRatioX96,
liquidity
);
} else {
amount1 = getAmount1ForLiquidity(
sqrtRatioAX96,
sqrtRatioBX96,
liquidity
);
}
}
}
contracts/pancake/TickMath.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO =
1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick)
internal
pure
returns (uint160 sqrtPriceX96)
{
uint256 absTick =
tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
// EDIT: 0.8 compatibility
require(absTick <= uint256(int256(MAX_TICK)), "T");
uint256 ratio =
absTick & 0x1 != 0
? 0xfffcb933bd6fad37aa2d162d1a594001
: 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0)
ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0)
ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0)
ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0)
ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0)
ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0)
ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0)
ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0)
ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0)
ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0)
ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0)
ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0)
ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0)
ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0)
ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0)
ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0)
ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0)
ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0)
ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0)
ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160(
(ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)
);
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96)
internal
pure
returns (int24 tick)
{
// second inequality must be < because the price can never reach the price at the max tick
require(
sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO,
"R"
);
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow =
int24(
(log_sqrt10001 - 3402992956809132418596140100660247210) >> 128
);
int24 tickHi =
int24(
(log_sqrt10001 + 291339464771989622907027621153398088495) >> 128
);
tick = tickLow == tickHi
? tickLow
: getSqrtRatioAtTick(tickHi) <= sqrtPriceX96
? tickHi
: tickLow;
}
}
contracts/pancake/interfaces/IPancakeV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.4;
/// @title The interface for a PancakeSwap V3 Pool
/// @notice A PancakeSwap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IPancakeV3Pool {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint32 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(
int24 tick
)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(
bytes32 key
)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(
uint256 index
)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
/// @notice The contract that deployed the pool, which must adhere to the IPancakeV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IPancakeV3MintCallback#pancakeV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IPancakeV3SwapCallback#pancakeV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IPancakeV3FlashCallback#pancakeV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
contracts/pancake/interfaces/callback/IPancakeV3MintCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.4;
/// @title Callback for IPancakeV3PoolActions#mint
/// @notice Any contract that calls IPancakeV3PoolActions#mint must implement this interface
interface IPancakeV3MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IPancakeV3Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method must be checked to be a PancakeV3Pool deployed by the canonical PancakeV3Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IPancakeV3PoolActions#mint call
function pancakeV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
contracts/pancake/interfaces/callback/IPancakeV3SwapCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.4;
/// @title Callback for IPancakeV3PoolActions#swap
/// @notice Any contract that calls IPancakeV3PoolActions#swap must implement this interface
interface IPancakeV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IPancakeV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a PancakeV3Pool deployed by the canonical PancakeV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IPancakeV3PoolActions#swap call
function pancakeV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {
"contracts/libraries/VaultLib.sol": {
"VaultLib": "0xb0f6b84ee516005a475fbc335c949edd17754c19"
}
},
"optimizer": {
"runs": 100,
"enabled": true
},
"evmVersion": "istanbul",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.