Verified contractPartialBUSL-1.1
NamiPluginV1WithAntiSniperExtension
Address0xacab1154217ca350ff03cc4e9617a4e997e0ae1f
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.20
- Same code
Only this contract
Details
- Compiler
- solc 0.8.20+commit.a1b79de6
- Language
- solidity
- Optimization
- Yes, 0 runs
- EVM version
- paris
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,295,105
- Creation transaction
- 0xf9a75871aa…09c5b7e124
60 files
- contracts/plugins/extensions/NamiPluginV1WithAntiSniperExtension.solmain1.38 KB
- @cryptoalgebra/abstract-plugin/contracts/UpgradeableAbstractPlugin.sol5.78 KB
- @cryptoalgebra/abstract-plugin/contracts/interfaces/IAbstractPlugin.sol790 B
- @cryptoalgebra/abstract-plugin/contracts/interfaces/IAlgebraPluginProxy.sol162 B
- @cryptoalgebra/dynamic-fee-plugin/contracts/interfaces/IDynamicFeeManager.sol1.05 KB
- @cryptoalgebra/dynamic-fee-plugin/contracts/libraries/AdaptiveFee.sol5.57 KB
- @cryptoalgebra/dynamic-fee-plugin/contracts/libraries/DynamicFeeStorage.sol720 B
- @cryptoalgebra/dynamic-fee-plugin/contracts/types/AlgebraFeeConfiguration.sol647 B
- @cryptoalgebra/dynamic-fee-plugin/contracts/types/AlgebraFeeConfigurationU144.sol2.69 KB
- @cryptoalgebra/farming-proxy-plugin/contracts/interfaces/IAlgebraVirtualPool.sol611 B
- @cryptoalgebra/farming-proxy-plugin/contracts/interfaces/IFarmingPlugin.sol1.59 KB
- @cryptoalgebra/farming-proxy-plugin/contracts/interfaces/IFarmingPluginFactory.sol828 B
- @cryptoalgebra/farming-proxy-plugin/contracts/libraries/FarmingProxyStorage.sol650 B
- @cryptoalgebra/integral-core/contracts/base/common/Timestamp.sol589 B
- @cryptoalgebra/integral-core/contracts/interfaces/IAlgebraFactory.sol10.77 KB
- @cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol975 B
- @cryptoalgebra/integral-core/contracts/interfaces/plugin/IAlgebraDynamicFeePlugin.sol633 B
- @cryptoalgebra/integral-core/contracts/interfaces/plugin/IAlgebraPlugin.sol7.24 KB
- @cryptoalgebra/integral-core/contracts/interfaces/plugin/IAlgebraPluginFactory.sol1.25 KB
- @cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolActions.sol7.82 KB
- @cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolErrors.sol4.21 KB
- @cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolEvents.sol6.39 KB
- @cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolImmutables.sol1.26 KB
- @cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolPermissionedActions.sol2.34 KB
- @cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolState.sol11.63 KB
- @cryptoalgebra/integral-core/contracts/interfaces/vault/IAlgebraVaultFactory.sol944 B
- @cryptoalgebra/integral-core/contracts/libraries/Constants.sol1.48 KB
- @cryptoalgebra/integral-core/contracts/libraries/Plugins.sol1.16 KB
- @cryptoalgebra/integral-core/contracts/libraries/SafeTransfer.sol3.39 KB
- @cryptoalgebra/volatility-oracle-plugin/contracts/interfaces/IVolatilityOracle.sol4.25 KB
- @cryptoalgebra/volatility-oracle-plugin/contracts/libraries/VolatilityOracle.sol29.51 KB
- @cryptoalgebra/volatility-oracle-plugin/contracts/libraries/VolatilityOracleStorage.sol841 B
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol6.63 KB
- @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol8.28 KB
- contracts/interfaces/mevx/IMevxExecutor.sol242 B
- contracts/interfaces/mevx/IMevxPlugin.sol2.52 KB
- contracts/interfaces/mevx/IMevxRouter.sol668 B
- contracts/interfaces/mevx/IProfitDistributor.sol249 B
- contracts/interfaces/plugins/IAntiSniperConnector.sol2.76 KB
- contracts/interfaces/plugins/INamiFeeOverride.sol2.96 KB
- contracts/interfaces/plugins/INamiFeeSource.sol972 B
- contracts/interfaces/plugins/INamiFeeSourceConsumer.sol1.79 KB
- contracts/libraries/AntiSniperStorage.sol816 B
- contracts/libraries/FeeOverrideStorage.sol1.26 KB
- contracts/libraries/MevxStorage.sol727 B
- contracts/plugins/extensions/NamiPluginV1ExtensionBase.sol1.97 KB
- contracts/plugins/modules/AntiSniperModuleUpgradeable.sol7.5 KB
- contracts/plugins/modules/DynamicFeeModuleUpgradeable.sol1.66 KB
- contracts/plugins/modules/FarmingProxyModuleUpgradeable.sol1.04 KB
- contracts/plugins/modules/FeeCurveModuleUpgradeable.sol811 B
- contracts/plugins/modules/FeeOverrideModuleUpgradeable.sol3.4 KB
- contracts/plugins/modules/MevxModuleUpgradeable.sol4.31 KB
- contracts/plugins/modules/VolatilityOracleModuleUpgradeable.sol2.19 KB
- contracts/plugins/modules/extensions/AntiSniperExtensionModule.sol2.74 KB
- contracts/plugins/modules/extensions/DynamicFeeExtensionModule.sol1.28 KB
- contracts/plugins/modules/extensions/FarmingProxyExtensionModule.sol2.79 KB
- contracts/plugins/modules/extensions/FeeOverrideExtensionModule.sol6.47 KB
- contracts/plugins/modules/extensions/MevxExtensionModule.sol4.17 KB
- contracts/plugins/modules/extensions/VolatilityOracleExtensionModule.sol3.57 KB
- solady/src/utils/FixedPointMathLib.sol55.69 KB
contracts/plugins/extensions/NamiPluginV1WithAntiSniperExtension.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import './NamiPluginV1ExtensionBase.sol';
import '../modules/extensions/AntiSniperExtensionModule.sol';
/// @title Nami Plugin V1 with AntiSniper extension
/// @notice Views and setters for NamiPluginV1WithAntiSniperDiamond
contract NamiPluginV1WithAntiSniperExtension is NamiPluginV1ExtensionBase, AntiSniperExtensionModule {
constructor(address _factory, address _pluginFactory) NamiPluginV1ExtensionBase(_factory, _pluginFactory) {}
/// @dev Shadowed by the hot implementation, kept so the contract is complete
function getActiveModuleNames() external pure override returns (string[] memory) {
string[] memory activeModules = new string[](6);
activeModules[0] = VOLATILITY_ORACLE_MODULE_NAME;
activeModules[1] = DYNAMIC_FEE_MODULE_NAME;
activeModules[2] = FARMING_PROXY_MODULE_NAME;
activeModules[3] = MEVX_MODULE_NAME;
activeModules[4] = ANTI_SNIPER_MODULE_NAME;
activeModules[5] = FEE_OVERRIDE_MODULE_NAME;
return activeModules;
}
/// @dev Shadowed by the hot implementation, kept so the contract is complete
function defaultPluginConfig() public pure override returns (uint8) {
return
VOLATILITY_ORACLE_PLUGIN_CONFIG |
DYNAMIC_FEE_PLUGIN_CONFIG |
FARMING_PROXY_PLUGIN_CONFIG |
MEVX_PLUGIN_CONFIG |
ANTI_SNIPER_PLUGIN_CONFIG;
}
}
@cryptoalgebra/abstract-plugin/contracts/UpgradeableAbstractPlugin.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import '@cryptoalgebra/integral-core/contracts/base/common/Timestamp.sol';
import '@cryptoalgebra/integral-core/contracts/libraries/Plugins.sol';
import '@cryptoalgebra/integral-core/contracts/libraries/SafeTransfer.sol';
import '@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraFactory.sol';
import '@cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolState.sol';
import '@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol';
import '@cryptoalgebra/integral-core/contracts/interfaces/plugin/IAlgebraPlugin.sol';
import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
import './interfaces/IAbstractPlugin.sol';
import './interfaces/IAlgebraPluginProxy.sol';
/// @title Algebra Integral 1.2.2 Upgradeable Abstract Plugin
/// @notice Base contract for upgradeable plugins using Beacon Proxy pattern
abstract contract UpgradeableAbstractPlugin is Initializable, IAbstractPlugin, Timestamp {
using Plugins for uint8;
/// @dev Offset in AlgebraPluginProxy bytecode
uint256 public constant POOL_ADDRESS_OFFSET = 75;
/// @dev The role can be granted in AlgebraFactory
bytes32 public constant ALGEBRA_BASE_PLUGIN_MANAGER = keccak256('ALGEBRA_BASE_PLUGIN_MANAGER');
/// @dev shared across all proxies
address public immutable factory;
/// @dev shared across all proxies
address public immutable pluginFactory;
modifier onlyPool() {
_checkIfFromPool();
_;
}
modifier onlyPluginFactory() {
if (msg.sender != pluginFactory) revert OnlyPluginFactory();
_;
}
constructor(address _factory, address _pluginFactory) {
factory = _factory;
pluginFactory = _pluginFactory;
_disableInitializers();
}
/// @dev Reads the pool address embedded in the proxy's bytecode.
function _getPool() internal view virtual returns (address) {
bytes32 word;
assembly {
let ptr := mload(0x40)
extcodecopy(address(), ptr, POOL_ADDRESS_OFFSET, 32)
word := mload(ptr)
}
return address(uint160(uint256(word)));
}
function _checkIfFromPool() internal view {
if (msg.sender != _getPool()) revert OnlyPool();
}
function _authorize() internal view virtual {
if (!IAlgebraFactory(factory).hasRoleOrOwner(ALGEBRA_BASE_PLUGIN_MANAGER, msg.sender)) revert OnlyAdministrator();
}
function _getPoolState() internal view virtual returns (uint160 price, int24 tick, uint16 fee, uint8 pluginConfig) {
(price, tick, fee, pluginConfig, , ) = IAlgebraPoolState(_getPool()).globalState();
}
function _getPluginInPool() internal view returns (address plugin) {
return IAlgebraPool(_getPool()).plugin();
}
function pool() public view returns (address) {
return _getPool();
}
/// @inheritdoc IAbstractPlugin
/// @dev must be implemented by the default plugin
function getActiveModuleNames() external view virtual override returns (string[] memory moduleNames);
/// @notice Returns the default plugin config
/// @dev Must be implemented by the default plugin, used to sync config into the pool
function defaultPluginConfig() public view virtual returns (uint8);
/// @inheritdoc IAbstractPlugin
function collectPluginFee(address token, uint256 amount, address recipient) external virtual override {
_authorize();
SafeTransfer.safeTransfer(token, recipient, amount);
}
/// @inheritdoc IAlgebraPlugin
function handlePluginFee(uint256, uint256) external view virtual override onlyPool returns (bytes4) {
return IAlgebraPlugin.handlePluginFee.selector;
}
// ###### HOOKS ######
function beforeInitialize(address, uint160) external virtual override onlyPool returns (bytes4) {
return IAlgebraPlugin.beforeInitialize.selector;
}
function afterInitialize(address, uint160, int24) external virtual override onlyPool returns (bytes4) {
return IAlgebraPlugin.afterInitialize.selector;
}
function beforeModifyPosition(
address,
address,
int24,
int24,
int128,
bytes calldata
) external virtual override onlyPool returns (bytes4, uint24) {
return (IAlgebraPlugin.beforeModifyPosition.selector, 0);
}
function afterModifyPosition(
address,
address,
int24,
int24,
int128,
uint256,
uint256,
bytes calldata
) external virtual override onlyPool returns (bytes4) {
return IAlgebraPlugin.afterModifyPosition.selector;
}
function beforeSwap(
address,
address,
bool,
int256,
uint160,
bool,
bytes calldata
) external virtual override onlyPool returns (bytes4, uint24, uint24) {
return (IAlgebraPlugin.beforeSwap.selector, 0, 0);
}
function afterSwap(
address,
address,
bool,
int256,
uint160,
int256,
int256,
bytes calldata
) external virtual override onlyPool returns (bytes4) {
return IAlgebraPlugin.afterSwap.selector;
}
function beforeFlash(address, address, uint256, uint256, bytes calldata) external virtual override onlyPool returns (bytes4) {
return IAlgebraPlugin.beforeFlash.selector;
}
function afterFlash(
address,
address,
uint256,
uint256,
uint256,
uint256,
bytes calldata
) external virtual override onlyPool returns (bytes4) {
return IAlgebraPlugin.afterFlash.selector;
}
function _updatePluginConfigInPool(uint8 newPluginConfig) internal {
(, , , uint8 currentPluginConfig) = _getPoolState();
if (currentPluginConfig != newPluginConfig) {
IAlgebraPool(_getPool()).setPluginConfig(newPluginConfig);
}
}
}
@cryptoalgebra/abstract-plugin/contracts/interfaces/IAbstractPlugin.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma abicoder v2;
import '@cryptoalgebra/integral-core/contracts/interfaces/plugin/IAlgebraPlugin.sol';
/// @title The interface for the BasePlugin
interface IAbstractPlugin is IAlgebraPlugin {
error OnlyPool();
error OnlyPluginFactory();
error OnlyAdministrator();
/// @notice Claim plugin fee
/// @param token The token address
/// @param amount Amount of tokens
/// @param recipient Recipient address
function collectPluginFee(address token, uint256 amount, address recipient) external;
/// @notice Get all active module names
/// @return moduleNames Array of active module names
function getActiveModuleNames() external view returns (string[] memory moduleNames);
}
@cryptoalgebra/abstract-plugin/contracts/interfaces/IAlgebraPluginProxy.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
interface IAlgebraPluginProxy {
function pool() external view returns (address);
}
@cryptoalgebra/dynamic-fee-plugin/contracts/interfaces/IDynamicFeeManager.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma abicoder v2;
import '@cryptoalgebra/integral-core/contracts/interfaces/plugin/IAlgebraDynamicFeePlugin.sol';
import '../types/AlgebraFeeConfiguration.sol';
/// @title The interface for the Algebra dynamic fee manager
/// @dev This contract calculates adaptive fee
interface IDynamicFeeManager is IAlgebraDynamicFeePlugin {
/// @notice Emitted when the fee configuration is changed
/// @param feeConfig The structure with dynamic fee parameters
/// @dev See the AdaptiveFee struct for more details
event FeeConfiguration(AlgebraFeeConfiguration feeConfig);
/// @notice Current dynamic fee configuration
/// @dev See the AdaptiveFee struct for more details
function feeConfig()
external
view
returns (uint16 alpha1, uint16 alpha2, uint32 beta1, uint32 beta2, uint16 gamma1, uint16 gamma2, uint16 baseFee);
/// @notice Changes fee configuration for the pool
function changeFeeConfiguration(AlgebraFeeConfiguration calldata feeConfig) external;
}
@cryptoalgebra/dynamic-fee-plugin/contracts/libraries/AdaptiveFee.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '@cryptoalgebra/integral-core/contracts/libraries/Constants.sol';
import '../types/AlgebraFeeConfiguration.sol';
import '../types/AlgebraFeeConfigurationU144.sol';
/// @title AdaptiveFee
/// @notice Calculates fee based on combination of sigmoids
library AdaptiveFee {
uint16 internal constant INITIAL_MIN_FEE = 0.01e4; // 0.01%
/// @notice Returns default initial fee configuration
function initialFeeConfiguration() internal pure returns (AlgebraFeeConfiguration memory) {
return
AlgebraFeeConfiguration({
alpha1: 3000 - INITIAL_MIN_FEE, // max value of the first sigmoid in hundredths of a bip, i.e. 1e-6
alpha2: 15000 - 3000, // max value of the second sigmoid in hundredths of a bip, i.e. 1e-6
beta1: 360, // shift along the x-axis (volatility) for the first sigmoid
beta2: 60000, // shift along the x-axis (volatility) for the second sigmoid
gamma1: 59, // horizontal stretch factor for the first sigmoid
gamma2: 8500, // horizontal stretch factor for the second sigmoid
baseFee: INITIAL_MIN_FEE // in hundredths of a bip, i.e. 1e-6
});
}
/// @notice Validates fee configuration.
/// @dev Maximum fee value capped by baseFee + alpha1 + alpha2 must be <= type(uint16).max
/// gammas must be > 0
function validateFeeConfiguration(AlgebraFeeConfiguration memory _config) internal pure {
require(uint256(_config.alpha1) + uint256(_config.alpha2) + uint256(_config.baseFee) <= type(uint16).max, 'Max fee exceeded');
require(_config.gamma1 != 0 && _config.gamma2 != 0, 'Gammas must be > 0');
}
/// @notice Calculates fee based on formula:
/// baseFee + sigmoid1(volatility) + sigmoid2(volatility)
/// maximum value capped by baseFee + alpha1 + alpha2
function getFee(uint88 volatility, AlgebraFeeConfigurationU144 config) internal pure returns (uint16 fee) {
unchecked {
volatility /= 15; // normalize for 15 sec interval
uint256 sumOfSigmoids = sigmoid(volatility, config.gamma1(), config.alpha1(), config.beta1()) +
sigmoid(volatility, config.gamma2(), config.alpha2(), config.beta2());
uint256 result = uint256(config.baseFee()) + sumOfSigmoids;
assert(result <= type(uint16).max); // should always be true
return uint16(result); // safe since alpha1 + alpha2 + baseFee _must_ be <= type(uint16).max
}
}
/// @notice calculates α / (1 + e^( (β-x) / γ))
/// that is a sigmoid with a maximum value of α, x-shifted by β, and stretched by γ
/// @dev returns uint256 for fuzzy testing. Guaranteed that the result is not greater than alpha
function sigmoid(uint256 x, uint16 g, uint16 alpha, uint256 beta) internal pure returns (uint256 res) {
unchecked {
if (x > beta) {
x = x - beta;
if (x >= 6 * uint256(g)) return alpha; // so x < 19 bits
uint256 g4 = uint256(g) ** 4; // < 64 bits (4*16)
uint256 ex = expXg4(x, g, g4); // < 155 bits
res = (alpha * ex) / (g4 + ex); // in worst case: (16 + 155 bits) / 155 bits
// so res <= alpha
} else {
x = beta - x;
if (x >= 6 * uint256(g)) return 0; // so x < 19 bits
uint256 g4 = uint256(g) ** 4; // < 64 bits (4*16)
uint256 ex = g4 + expXg4(x, g, g4); // < 156 bits
res = (alpha * g4) / ex; // in worst case: (16 + 128 bits) / 156 bits
// g8 <= ex, so res <= alpha
}
}
}
/// @notice calculates e^(x/g) * g^4 in a series, since (around zero):
/// e^x = 1 + x + x^2/2 + ... + x^n/n! + ...
/// e^(x/g) = 1 + x/g + x^2/(2*g^2) + ... + x^(n)/(g^n * n!) + ...
/// @dev has good accuracy only if x/g < 6
function expXg4(uint256 x, uint16 g, uint256 gHighestDegree) internal pure returns (uint256 res) {
uint256 closestValue; // nearest 'table' value of e^(x/g), multiplied by 10^20
assembly {
let xdg := div(x, g)
switch xdg
case 0 {
closestValue := 100000000000000000000 // 1
}
case 1 {
closestValue := 271828182845904523536 // ~= e
}
case 2 {
closestValue := 738905609893065022723 // ~= e^2
}
case 3 {
closestValue := 2008553692318766774092 // ~= e^3
}
case 4 {
closestValue := 5459815003314423907811 // ~= e^4
}
default {
closestValue := 14841315910257660342111 // ~= e^5
}
x := mod(x, g)
}
unchecked {
if (x >= g / 2) {
// (x - closestValue) >= 0.5, so closestValue := closestValue * e^0.5
x -= g / 2;
closestValue = (closestValue * 164872127070012814684) / 1e20;
}
// After calculating the closestValue x/g is <= 0.5, so that the series in the neighborhood of zero converges with sufficient speed
uint256 xLowestDegree = x;
res = gHighestDegree; // g**4, res < 64 bits
gHighestDegree /= g; // g**3
res += xLowestDegree * gHighestDegree; // g**4 + x*g**3, res < 68
gHighestDegree /= g; // g**2
xLowestDegree *= x; // x**2
// g**4 + x * g**3 + (x**2 * g**2) / 2, res < 71
res += (xLowestDegree * gHighestDegree) / 2;
gHighestDegree /= g; // g
xLowestDegree *= x; // x**3
// g^4 + x * g^3 + (x^2 * g^2)/2 + x^3(g*4 + x)/24, res < 73
res += (xLowestDegree * g * 4 + xLowestDegree * x) / 24;
// res = g^4 * (1 + x/g + x^2/(2*g^2) + x^3/(6*g^3) + x^4/(24*g^4)) * closestValue / 10^20, closestValue < 75 bits, res < 155
res = (res * closestValue) / (1e20);
}
}
}
@cryptoalgebra/dynamic-fee-plugin/contracts/libraries/DynamicFeeStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import { AlgebraFeeConfigurationU144 } from '../types/AlgebraFeeConfigurationU144.sol';
/// @dev Shared namespaced storage for DynamicFee plugin (used by connector + implementation).
library DynamicFeeStorage {
/// @dev keccak256(abi.encode(uint256(keccak256("erc7201:algebra.storage.dynamicfee")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant NAMESPACE = 0xfbbf1a562c70d290e080160018965a1e5db682cf55e666eca8f391a4ceef9a00;
struct Layout {
AlgebraFeeConfigurationU144 feeConfig;
}
function layout() internal pure returns (Layout storage l) {
bytes32 position = NAMESPACE;
assembly {
l.slot := position
}
}
}
@cryptoalgebra/dynamic-fee-plugin/contracts/types/AlgebraFeeConfiguration.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @notice coefficients for sigmoids: α / (1 + e^( (β-x) / γ))
/// @dev alpha1 + alpha2 + baseFee must be <= type(uint16).max
struct AlgebraFeeConfiguration {
uint16 alpha1; // max value of the first sigmoid
uint16 alpha2; // max value of the second sigmoid
uint32 beta1; // shift along the x-axis for the first sigmoid
uint32 beta2; // shift along the x-axis for the second sigmoid
uint16 gamma1; // horizontal stretch factor for the first sigmoid
uint16 gamma2; // horizontal stretch factor for the second sigmoid
uint16 baseFee; // minimum possible fee
}
@cryptoalgebra/dynamic-fee-plugin/contracts/types/AlgebraFeeConfigurationU144.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import './AlgebraFeeConfiguration.sol';
type AlgebraFeeConfigurationU144 is uint144;
using AlgebraFeeConfigurationU144Lib for AlgebraFeeConfigurationU144 global;
/// @title AdaptiveFee packed configuration library
/// @notice Used to interact with uint144-packed fee config
/// @dev Structs are not packed in storage with neighboring values, but uint144 can be packed
library AlgebraFeeConfigurationU144Lib {
uint256 private constant UINT16_MASK = 0xFFFF;
uint256 private constant UINT32_MASK = 0xFFFFFFFF;
// alpha1 offset is 0
uint256 private constant ALPHA2_OFFSET = 16;
uint256 private constant BETA1_OFFSET = 32;
uint256 private constant BETA2_OFFSET = 64;
uint256 private constant GAMMA1_OFFSET = 96;
uint256 private constant GAMMA2_OFFSET = 112;
uint256 private constant BASE_FEE_OFFSET = 128;
function pack(AlgebraFeeConfiguration memory config) internal pure returns (AlgebraFeeConfigurationU144) {
uint144 _config = uint144(
(uint256(config.baseFee) << BASE_FEE_OFFSET) |
(uint256(config.gamma2) << GAMMA2_OFFSET) |
(uint256(config.gamma1) << GAMMA1_OFFSET) |
(uint256(config.beta2) << BETA2_OFFSET) |
(uint256(config.beta1) << BETA1_OFFSET) |
(uint256(config.alpha2) << ALPHA2_OFFSET) |
uint256(config.alpha1)
);
return AlgebraFeeConfigurationU144.wrap(_config);
}
function alpha1(AlgebraFeeConfigurationU144 config) internal pure returns (uint16 _alpha1) {
assembly {
_alpha1 := and(UINT16_MASK, config)
}
}
function alpha2(AlgebraFeeConfigurationU144 config) internal pure returns (uint16 _alpha2) {
assembly {
_alpha2 := and(UINT16_MASK, shr(ALPHA2_OFFSET, config))
}
}
function beta1(AlgebraFeeConfigurationU144 config) internal pure returns (uint32 _beta1) {
assembly {
_beta1 := and(UINT32_MASK, shr(BETA1_OFFSET, config))
}
}
function beta2(AlgebraFeeConfigurationU144 config) internal pure returns (uint32 _beta2) {
assembly {
_beta2 := and(UINT32_MASK, shr(BETA2_OFFSET, config))
}
}
function gamma1(AlgebraFeeConfigurationU144 config) internal pure returns (uint16 _gamma1) {
assembly {
_gamma1 := and(UINT16_MASK, shr(GAMMA1_OFFSET, config))
}
}
function gamma2(AlgebraFeeConfigurationU144 config) internal pure returns (uint16 _gamma2) {
assembly {
_gamma2 := and(UINT16_MASK, shr(GAMMA2_OFFSET, config))
}
}
function baseFee(AlgebraFeeConfigurationU144 config) internal pure returns (uint16 _baseFee) {
assembly {
_baseFee := and(UINT16_MASK, shr(BASE_FEE_OFFSET, config))
}
}
}
@cryptoalgebra/farming-proxy-plugin/contracts/interfaces/IAlgebraVirtualPool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the virtual pool
/// @dev Used to calculate active liquidity in farmings
interface IAlgebraVirtualPool {
/// @dev This function is called by the main pool if an initialized ticks are crossed by swap.
/// If any one of crossed ticks is also initialized in a virtual pool it should be crossed too
/// @param targetTick The target tick up to which we need to cross all active ticks
/// @param zeroToOne Swap direction
function crossTo(int24 targetTick, bool zeroToOne) external returns (bool success);
}
@cryptoalgebra/farming-proxy-plugin/contracts/interfaces/IFarmingPlugin.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Algebra farming plugin
/// @dev This contract used for virtual pools in farms
interface IFarmingPlugin {
/// @notice Emitted when new activeIncentive is set
/// @param newIncentive The address of the new incentive
event Incentive(address newIncentive);
/// @notice Connects or disconnects an incentive.
/// @dev Only farming can connect incentives.
/// The one who connected it and the current farming has the right to disconnect the incentive.
/// @param newIncentive The address associated with the incentive or zero address
function setIncentive(address newIncentive) external;
/// @notice Checks if the incentive is connected to pool
/// @dev Returns false if the plugin has a different incentive set, the plugin is not connected to the pool,
/// or the plugin configuration is incorrect.
/// @param targetIncentive The address of the incentive to be checked
/// @return Indicates whether the target incentive is active
function isIncentiveConnected(address targetIncentive) external returns (bool);
/// @notice Returns the address of active incentive
/// @dev if there is no active incentive at the moment, incentiveAddress would be equal to address(0)
/// @return The address associated with the current active incentive
function incentive() external view returns (address);
/// @notice Returns the address of the pool the plugin is created for
/// @return address of the pool
function getPool() external view returns (address);
}
@cryptoalgebra/farming-proxy-plugin/contracts/interfaces/IFarmingPluginFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the PluginFactory which deploys FarmingProxyPlugin
/// @dev This contract contains function that must be implemented by the FarmingProxyPlugin' PluginFactory
interface IFarmingPluginFactory {
/// @notice Returns current farming address
/// @return The farming contract address
function farmingAddress() external view returns (address);
/// @dev updates farmings manager address on the factory
/// @param newFarmingAddress The new tokenomics contract address
function setFarmingAddress(address newFarmingAddress) external;
/// @notice Emitted when the farming address is changed
/// @param newFarmingAddress The farming address after the address was changed
event FarmingAddress(address newFarmingAddress);
}
@cryptoalgebra/farming-proxy-plugin/contracts/libraries/FarmingProxyStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
/// @dev Shared namespaced storage for FarmingProxy plugin (used by connector + implementation).
library FarmingProxyStorage {
/// @dev keccak256(abi.encode(uint256(keccak256("erc7201:algebra.storage.farmingproxy")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant NAMESPACE = 0xdefe014d06c76a87f6a6efbd410e650d6bcbb85e816546b55f626b436c8a1000;
struct Layout {
address incentive;
address lastIncentiveOwner;
}
function layout() internal pure returns (Layout storage l) {
bytes32 position = NAMESPACE;
assembly {
l.slot := position
}
}
}
@cryptoalgebra/integral-core/contracts/base/common/Timestamp.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0 <0.9.0;
/// @title Abstract contract with modified blockTimestamp functionality
/// @notice Allows the pool and other contracts to get a timestamp truncated to 32 bits
/// @dev Can be overridden in tests to make testing easier
abstract contract Timestamp {
/// @dev This function is created for testing by overriding it.
/// @return A timestamp converted to uint32
function _blockTimestamp() internal view virtual returns (uint32) {
return uint32(block.timestamp); // truncation is desired
}
}
@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma abicoder v2;
import './plugin/IAlgebraPluginFactory.sol';
import './vault/IAlgebraVaultFactory.sol';
/// @title The interface for the Algebra Factory
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraFactory {
/// @notice Emitted when a process of ownership renounce is started
/// @param timestamp The timestamp of event
/// @param finishTimestamp The timestamp when ownership renounce will be possible to finish
event RenounceOwnershipStart(uint256 timestamp, uint256 finishTimestamp);
/// @notice Emitted when a process of ownership renounce cancelled
/// @param timestamp The timestamp of event
event RenounceOwnershipStop(uint256 timestamp);
/// @notice Emitted when a process of ownership renounce finished
/// @param timestamp The timestamp of ownership renouncement
event RenounceOwnershipFinish(uint256 timestamp);
/// @notice Emitted when any pool is created, including custom pools
/// @dev Also emitted for custom pools, alongside CustomPool, so that indexers watching only
/// this event still discover the pool
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param pool The address of the created pool
event Pool(address indexed token0, address indexed token1, address pool);
/// @notice Emitted when a custom pool is created, in addition to Pool event
/// @param deployer The corresponding custom deployer contract
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param pool The address of the created pool
event CustomPool(address indexed deployer, address indexed token0, address indexed token1, address pool);
/// @notice Emitted when the default community fee is changed
/// @param newDefaultCommunityFee The new default community fee value
event DefaultCommunityFee(uint16 newDefaultCommunityFee);
/// @notice Emitted when the default tickspacing is changed
/// @param newDefaultTickspacing The new default tickspacing value
event DefaultTickspacing(int24 newDefaultTickspacing);
/// @notice Emitted when the default fee is changed
/// @param newDefaultFee The new default fee value
event DefaultFee(uint16 newDefaultFee);
/// @notice Emitted when the defaultPluginFactory address is changed
/// @param defaultPluginFactoryAddress The new defaultPluginFactory address
event DefaultPluginFactory(address defaultPluginFactoryAddress);
/// @notice Emitted when the vaultFactory address is changed
/// @param newVaultFactory The new vaultFactory address
event VaultFactory(address newVaultFactory);
/// @notice role that can change communityFee and tickspacing in pools
/// @return The hash corresponding to this role
function POOLS_ADMINISTRATOR_ROLE() external view returns (bytes32);
/// @notice role that can call `createCustomPool` function
/// @return The hash corresponding to this role
function CUSTOM_POOL_DEPLOYER() external view returns (bytes32);
/// @notice Returns `true` if `account` has been granted `role` or `account` is owner.
/// @param role The hash corresponding to the role
/// @param account The address for which the role is checked
/// @return bool Whether the address has this role or the owner role or not
function hasRoleOrOwner(bytes32 role, address account) external view returns (bool);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via transferOwnership(address newOwner)
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the current poolDeployerAddress
/// @return The address of the poolDeployer
function poolDeployer() external view returns (address);
/// @notice Returns the default community fee
/// @return Fee which will be set at the creation of the pool
function defaultCommunityFee() external view returns (uint16);
/// @notice Returns the default fee
/// @return Fee which will be set at the creation of the pool
function defaultFee() external view returns (uint16);
/// @notice Returns the default tickspacing
/// @return Tickspacing which will be set at the creation of the pool
function defaultTickspacing() external view returns (int24);
/// @notice Return the current pluginFactory address
/// @dev This contract is used to automatically set a plugin address in new liquidity pools
/// @return Algebra plugin factory
function defaultPluginFactory() external view returns (IAlgebraPluginFactory);
/// @notice Return the current vaultFactory address
/// @dev This contract is used to automatically set a vault address in new liquidity pools
/// @return Algebra vault factory
function vaultFactory() external view returns (IAlgebraVaultFactory);
/// @notice Returns the default communityFee, tickspacing, fee and communityFeeVault for pool
/// @return communityFee which will be set at the creation of the pool
/// @return tickSpacing which will be set at the creation of the pool
/// @return fee which will be set at the creation of the pool
function defaultConfigurationForPool() external view returns (uint16 communityFee, int24 tickSpacing, uint16 fee);
/// @notice Deterministically computes the pool address given the token0 and token1
/// @dev The method does not check if such a pool has been created
/// @param token0 first token
/// @param token1 second token
/// @return pool The contract address of the Algebra pool
function computePoolAddress(address token0, address token1) external view returns (address pool);
/// @notice Deterministically computes the custom pool address given the customDeployer, token0 and token1
/// @dev The method does not check if such a pool has been created
/// @param customDeployer the address of custom plugin deployer
/// @param token0 first token
/// @param token1 second token
/// @return customPool The contract address of the Algebra pool
function computeCustomPoolAddress(address customDeployer, address token0, address token1) external view returns (address customPool);
/// @notice Returns the pool address for a given pair of tokens, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @return pool The pool address
function poolByPair(address tokenA, address tokenB) external view returns (address pool);
/// @notice Returns the custom pool address for a customDeployer and a given pair of tokens, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param customDeployer The address of custom plugin deployer
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @return customPool The pool address
function customPoolByPair(address customDeployer, address tokenA, address tokenB) external view returns (address customPool);
/// @notice returns keccak256 of AlgebraPool init bytecode.
/// @dev the hash value changes with any change in the pool bytecode
/// @return Keccak256 hash of AlgebraPool contract init bytecode
function POOL_INIT_CODE_HASH() external view returns (bytes32);
/// @return timestamp The timestamp of the beginning of the renounceOwnership process
function renounceOwnershipStartTimestamp() external view returns (uint256 timestamp);
/// @notice Creates a pool for the given two tokens
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param data Data for plugin creation
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0.
/// The call will revert if the pool already exists or the token arguments are invalid.
/// @return pool The address of the newly created pool
function createPool(address tokenA, address tokenB, bytes calldata data) external returns (address pool);
/// @notice Creates a custom pool for the given two tokens using `deployer` contract
/// @param deployer The address of plugin deployer, also used for custom pool address calculation
/// @param creator The initiator of custom pool creation
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param data The additional data bytes
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0.
/// The call will revert if the pool already exists or the token arguments are invalid.
/// @return customPool The address of the newly created custom pool
function createCustomPool(
address deployer,
address creator,
address tokenA,
address tokenB,
bytes calldata data
) external returns (address customPool);
/// @dev updates default community fee for new pools
/// @param newDefaultCommunityFee The new community fee, _must_ be <= MAX_COMMUNITY_FEE
function setDefaultCommunityFee(uint16 newDefaultCommunityFee) external;
/// @dev updates default fee for new pools
/// @param newDefaultFee The new fee, _must_ be <= MAX_DEFAULT_FEE
function setDefaultFee(uint16 newDefaultFee) external;
/// @dev updates default tickspacing for new pools
/// @param newDefaultTickspacing The new tickspacing, _must_ be <= MAX_TICK_SPACING and >= MIN_TICK_SPACING
function setDefaultTickspacing(int24 newDefaultTickspacing) external;
/// @dev updates pluginFactory address
/// @param newDefaultPluginFactory address of new plugin factory
function setDefaultPluginFactory(address newDefaultPluginFactory) external;
/// @dev updates vaultFactory address
/// @param newVaultFactory address of new vault factory
function setVaultFactory(address newVaultFactory) external;
/// @notice Starts process of renounceOwnership. After that, a certain period
/// of time must pass before the ownership renounce can be completed.
function startRenounceOwnership() external;
/// @notice Stops process of renounceOwnership and removes timer.
function stopRenounceOwnership() external;
}
@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
import './pool/IAlgebraPoolImmutables.sol';
import './pool/IAlgebraPoolState.sol';
import './pool/IAlgebraPoolActions.sol';
import './pool/IAlgebraPoolPermissionedActions.sol';
import './pool/IAlgebraPoolEvents.sol';
import './pool/IAlgebraPoolErrors.sol';
/// @title The interface for a Algebra Pool
/// @dev The pool interface is broken up into many smaller pieces.
/// This interface includes custom error definitions and cannot be used in older versions of Solidity.
/// For older versions of Solidity use #IAlgebraPoolLegacy
/// Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPool is
IAlgebraPoolImmutables,
IAlgebraPoolState,
IAlgebraPoolActions,
IAlgebraPoolPermissionedActions,
IAlgebraPoolEvents,
IAlgebraPoolErrors
{
// used only for combining interfaces
}
@cryptoalgebra/integral-core/contracts/interfaces/plugin/IAlgebraDynamicFeePlugin.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Algebra plugin with dynamic fee logic
/// @dev A plugin with a dynamic fee must implement this interface so that the current fee can be known through the pool
/// If the dynamic fee logic does not allow the fee to be calculated without additional data, the method should revert with the appropriate message
interface IAlgebraDynamicFeePlugin {
/// @notice Returns fee from plugin
/// @return fee The pool fee value in hundredths of a bip, i.e. 1e-6
function getCurrentFee() external view returns (uint16 fee);
}
@cryptoalgebra/integral-core/contracts/interfaces/plugin/IAlgebraPlugin.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The Algebra plugin interface
/// @dev The plugin will be called by the pool using hook methods depending on the current pool settings
interface IAlgebraPlugin {
/// @notice Returns plugin config
/// @return config Each bit of the config is responsible for enabling/disabling the hooks.
/// The last bit indicates whether the plugin contains dynamic fees logic
function defaultPluginConfig() external view returns (uint8);
/// @notice Handle plugin fee transfer on plugin contract
/// @param pluginFee0 Fee0 amount transferred to plugin
/// @param pluginFee1 Fee1 amount transferred to plugin
/// @return bytes4 The function selector
function handlePluginFee(uint256 pluginFee0, uint256 pluginFee1) external returns (bytes4);
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, uint160 sqrtPriceX96, int24 tick) external returns (bytes4);
/// @notice The hook called before a position is modified
/// @param sender The initial msg.sender for the modify position call
/// @param recipient Address to which the liquidity will be assigned in case of a mint or
/// to which tokens will be sent in case of a burn
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param desiredLiquidityDelta The desired amount of liquidity to mint/burn
/// @param data Data that passed through the callback
/// @return selector The function selector for the hook
function beforeModifyPosition(
address sender,
address recipient,
int24 bottomTick,
int24 topTick,
int128 desiredLiquidityDelta,
bytes calldata data
) external returns (bytes4 selector, uint24 pluginFee);
/// @notice The hook called after a position is modified
/// @param sender The initial msg.sender for the modify position call
/// @param recipient Address to which the liquidity will be assigned in case of a mint or
/// to which tokens will be sent in case of a burn
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param desiredLiquidityDelta The desired amount of liquidity to mint/burn
/// @param amount0 The amount of token0 sent to the recipient or was paid to mint
/// @param amount1 The amount of token0 sent to the recipient or was paid to mint
/// @param data Data that passed through the callback
/// @return bytes4 The function selector for the hook
function afterModifyPosition(
address sender,
address recipient,
int24 bottomTick,
int24 topTick,
int128 desiredLiquidityDelta,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external returns (bytes4);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountRequired The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param limitSqrtPrice 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 withPaymentInAdvance The flag indicating whether the `swapWithPaymentInAdvance` method was called
/// @param data Data that passed through the callback
/// @return selector The function selector for the hook
function beforeSwap(
address sender,
address recipient,
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice,
bool withPaymentInAdvance,
bytes calldata data
) external returns (bytes4 selector, uint24 feeOverride, uint24 pluginFee);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountRequired The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param limitSqrtPrice 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 amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @param amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
/// @param data Data that passed through the callback
/// @return bytes4 The function selector for the hook
function afterSwap(
address sender,
address recipient,
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice,
int256 amount0,
int256 amount1,
bytes calldata data
) external returns (bytes4);
/// @notice The hook called before flash
/// @param sender The initial msg.sender for the flash call
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 being requested for flash
/// @param amount1 The amount of token1 being requested for flash
/// @param data Data that passed through the callback
/// @return bytes4 The function selector for the hook
function beforeFlash(address sender, address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external returns (bytes4);
/// @notice The hook called after flash
/// @param sender The initial msg.sender for the flash call
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 being requested for flash
/// @param amount1 The amount of token1 being requested for flash
/// @param paid0 The amount of token0 being paid for flash
/// @param paid1 The amount of token1 being paid for flash
/// @param data Data that passed through the callback
/// @return bytes4 The function selector for the hook
function afterFlash(
address sender,
address recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1,
bytes calldata data
) external returns (bytes4);
}
@cryptoalgebra/integral-core/contracts/interfaces/plugin/IAlgebraPluginFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title An interface for a contract that is capable of deploying Algebra plugins
/// @dev Such a factory can be used for automatic plugin creation for new pools.
/// Also a factory be used as an entry point for custom (additional) pools creation
interface IAlgebraPluginFactory {
/// @notice Deploys new plugin contract for pool
/// @param pool The address of the new pool
/// @param creator The address that initiated the pool creation
/// @param deployer The address of new plugin deployer contract (0 if not used)
/// @param token0 First token of the pool
/// @param token1 Second token of the pool
/// @return New plugin address
function beforeCreatePoolHook(
address pool,
address creator,
address deployer,
address token0,
address token1,
bytes calldata data
) external returns (address);
/// @notice Called after the pool is created
/// @param plugin The plugin address
/// @param pool The address of the new pool
/// @param deployer The address of new plugin deployer contract (0 if not used)
function afterCreatePoolHook(address plugin, address pool, address deployer) external;
}
@cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @dev Initialization should be done in one transaction with pool creation to avoid front-running
/// @param initialPrice The initial sqrt price of the pool as a Q64.96
function initialize(uint160 initialPrice) external;
/// @notice Adds liquidity for the given recipient/bottomTick/topTick position
/// @dev The caller of this method receives a callback in the form of IAlgebraMintCallback#algebraMintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on bottomTick, topTick, the amount of liquidity, and the current price.
/// @param leftoversRecipient The address which will receive potential surplus of paid tokens
/// @param recipient The address for which the liquidity will be created
/// @param bottomTick The lower tick of the position in which to add liquidity
/// @param topTick The upper tick of the position in which to add liquidity
/// @param liquidityDesired The desired 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
/// @return liquidityActual The actual minted amount of liquidity
function mint(
address leftoversRecipient,
address recipient,
int24 bottomTick,
int24 topTick,
uint128 liquidityDesired,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1, uint128 liquidityActual);
/// @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 bottomTick The lower tick of the position for which to collect fees
/// @param topTick 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 bottomTick,
int24 topTick,
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 bottomTick The lower tick of the position for which to burn liquidity
/// @param topTick The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @param data Any data that should be passed through to the plugin
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(int24 bottomTick, int24 topTick, uint128 amount, bytes calldata data) 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 IAlgebraSwapCallback#algebraSwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountRequired The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param limitSqrtPrice 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. If using the Router it should contain SwapRouter#SwapCallbackData
/// @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 zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Swap token0 for token1, or token1 for token0 with prepayment
/// @dev The caller of this method receives a callback in the form of IAlgebraSwapCallback#algebraSwapCallback
/// caller must send tokens in callback before swap calculation
/// the actually sent amount of tokens is used for further calculations
/// @param leftoversRecipient The address which will receive potential surplus of paid tokens
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountToSell The amount of the swap, only positive (exact input) amount allowed
/// @param limitSqrtPrice 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. If using the Router it should contain SwapRouter#SwapCallbackData
/// @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 swapWithPaymentInAdvance(
address leftoversRecipient,
address recipient,
bool zeroToOne,
int256 amountToSell,
uint160 limitSqrtPrice,
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 IAlgebraFlashCallback#algebraFlashCallback
/// @dev All excess tokens paid in the callback are distributed to currently in-range liquidity providers as an additional fee.
/// If there are no in-range liquidity providers, the fee will be transferred to the first active provider in the future
/// @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;
}
@cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolErrors.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
/// @title Errors emitted by a pool
/// @notice Contains custom errors emitted by the pool
/// @dev Custom errors are separated from the common pool interface for compatibility with older versions of Solidity
interface IAlgebraPoolErrors {
// #### pool errors ####
/// @notice Emitted by the reentrancy guard
error locked();
/// @notice Emitted if arithmetic error occurred
error arithmeticError();
/// @notice Emitted if an attempt is made to initialize the pool twice
error alreadyInitialized();
/// @notice Emitted if an attempt is made to mint or swap in uninitialized pool
error notInitialized();
/// @notice Emitted if 0 is passed as amountRequired to swap function
error zeroAmountRequired();
/// @notice Emitted if invalid amount is passed as amountRequired to swap function
error invalidAmountRequired();
/// @notice Emitted if plugin fee param greater than fee/override fee
error incorrectPluginFee();
/// @notice Emitted if the pool received fewer tokens than it should have
error insufficientInputAmount();
/// @notice Emitted if there was an attempt to mint zero liquidity
error zeroLiquidityDesired();
/// @notice Emitted if actual amount of liquidity is zero (due to insufficient amount of tokens received)
error zeroLiquidityActual();
/// @notice Emitted if the pool received fewer tokens0 after flash than it should have
error flashInsufficientPaid0();
/// @notice Emitted if the pool received fewer tokens1 after flash than it should have
error flashInsufficientPaid1();
/// @notice Emitted if limitSqrtPrice param is incorrect
error invalidLimitSqrtPrice();
/// @notice Tick must be divisible by tickspacing
error tickIsNotSpaced();
/// @notice Emitted if a method is called that is accessible only to the factory owner or dedicated role
error notAllowed();
/// @notice Emitted if new tick spacing exceeds max allowed value
error invalidNewTickSpacing();
/// @notice Emitted if new community fee exceeds max allowed value
error invalidNewCommunityFee();
/// @notice Emitted if an attempt is made to manually change the fee value, but dynamic fee is enabled
error dynamicFeeActive();
/// @notice Emitted if an attempt is made by plugin to change the fee value, but dynamic fee is disabled
error dynamicFeeDisabled();
/// @notice Emitted if an attempt is made to change the plugin configuration, but the plugin is not connected
error pluginIsNotConnected();
/// @notice Emitted if a plugin returns invalid selector after hook call
/// @param expectedSelector The expected selector
error invalidHookResponse(bytes4 expectedSelector);
// #### LiquidityMath errors ####
/// @notice Emitted if liquidity underflows
error liquiditySub();
/// @notice Emitted if liquidity overflows
error liquidityAdd();
// #### TickManagement errors ####
/// @notice Emitted if the topTick param not greater then the bottomTick param
error topTickLowerOrEqBottomTick();
/// @notice Emitted if the bottomTick param is lower than min allowed value
error bottomTickLowerThanMIN();
/// @notice Emitted if the topTick param is greater than max allowed value
error topTickAboveMAX();
/// @notice Emitted if the liquidity value associated with the tick exceeds MAX_LIQUIDITY_PER_TICK
error liquidityOverflow();
/// @notice Emitted if an attempt is made to interact with an uninitialized tick
error tickIsNotInitialized();
/// @notice Emitted if there is an attempt to insert a new tick into the list of ticks with incorrect indexes of the previous and next ticks
error tickInvalidLinks();
// #### SafeTransfer errors ####
/// @notice Emitted if token transfer failed internally
error transferFailed();
// #### TickMath errors ####
/// @notice Emitted if tick is greater than the maximum or less than the minimum allowed value
error tickOutOfRange();
/// @notice Emitted if price is greater than the maximum or less than the minimum allowed value
error priceOutOfRange();
}
@cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swaps cannot be emitted by the pool before Initialize
/// @param price The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 price, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param liquidityAmount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed bottomTick,
int24 indexed topTick,
uint128 liquidityAmount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @param owner The owner of the position for which fees are collected
/// @param recipient The address that received fees
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(address indexed owner, address recipient, int24 indexed bottomTick, int24 indexed topTick, uint128 amount0, uint128 amount1);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param liquidityAmount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed bottomTick,
int24 indexed topTick,
uint128 liquidityAmount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when a plugin fee is applied during a burn
/// @param owner The owner of the position
/// @param pluginFee The fee to be sent to the plugin
event BurnFee(address indexed owner, uint24 pluginFee);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param price The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 price,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool after any swaps
/// @param sender The address that initiated the swap
/// @param overrideFee The fee to be applied to the trade
/// @param pluginFee The fee to be sent to the plugin
event SwapFee(address indexed sender, uint24 overrideFee, uint24 pluginFee);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1);
/// @notice Emitted when the pool has higher balances than expected.
/// Any excess of tokens will be distributed between liquidity providers as fee.
/// @dev Fees after flash also will trigger this event due to mechanics of flash.
/// @param amount0 The excess of token0
/// @param amount1 The excess of token1
event ExcessTokens(uint256 amount0, uint256 amount1);
/// @notice Emitted when the community fee is changed by the pool
/// @param communityFeeNew The updated value of the community fee in thousandths (1e-3)
event CommunityFee(uint16 communityFeeNew);
/// @notice Emitted when the tick spacing changes
/// @param newTickSpacing The updated value of the new tick spacing
event TickSpacing(int24 newTickSpacing);
/// @notice Emitted when the plugin address changes
/// @param newPluginAddress New plugin address
event Plugin(address newPluginAddress);
/// @notice Emitted when the plugin config changes
/// @param newPluginConfig New plugin config
event PluginConfig(uint8 newPluginConfig);
/// @notice Emitted when the fee changes inside the pool
/// @param fee The current fee in hundredths of a bip, i.e. 1e-6
event Fee(uint16 fee);
/// @notice Emitted when the community vault address changes
/// @param newCommunityVault New community vault
event CommunityVault(address newCommunityVault);
/// @notice Emitted when the plugin does skim the excess of tokens
/// @param to THe receiver of tokens (plugin)
/// @param amount0 The amount of token0
/// @param amount1 The amount of token1
event Skim(address indexed to, uint256 amount0, uint256 amount1);
}
@cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolImmutables {
/// @notice The Algebra factory contract, which must adhere to the IAlgebraFactory 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 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);
}
@cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolPermissionedActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by permissioned addresses
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolPermissionedActions {
/// @notice Set the community's % share of the fees. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newCommunityFee The new community fee percent in thousandths (1e-3)
function setCommunityFee(uint16 newCommunityFee) external;
/// @notice Set the new tick spacing values. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newTickSpacing The new tick spacing value
function setTickSpacing(int24 newTickSpacing) external;
/// @notice Set the new plugin address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newPluginAddress The new plugin address
function setPlugin(address newPluginAddress) external;
/// @notice Set new plugin config. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newConfig In the new configuration of the plugin,
/// each bit of which is responsible for a particular hook.
function setPluginConfig(uint8 newConfig) external;
/// @notice Set new community fee vault address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @dev Community fee vault receives collected community fees.
/// **accumulated but not yet sent to the vault community fees once will be sent to the `newCommunityVault` address**
/// @param newCommunityVault The address of new community fee vault
function setCommunityVault(address newCommunityVault) external;
/// @notice Set new pool fee. Can be called by owner if dynamic fee is disabled.
/// Called by the plugin if dynamic fee is enabled
/// @param newFee The new fee value
function setFee(uint16 newFee) external;
/// @notice Forces balances to match reserves. Excessive tokens will be distributed between active LPs
/// @dev Only plugin can call this function
function sync() external;
/// @notice Forces balances to match reserves. Excessive tokens will be sent to msg.sender
/// @dev Only plugin can call this function
function skim() external;
}
@cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @dev Important security note: when using this data by external contracts, it is necessary to take into account the possibility
/// of manipulation (including read-only reentrancy).
/// This interface is based on the UniswapV3 interface, credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolState {
/// @notice Safely get most important state values of Algebra Integral AMM
/// @dev Several values exposed as a single method to save gas when accessed externally.
/// **Important security note: this method checks reentrancy lock and should be preferred in most cases**.
/// @return sqrtPrice The current price of the pool as a sqrt(dToken1/dToken0) Q64.96 value
/// @return tick The current global tick of the pool. May not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick boundary
/// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin
/// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
/// @return activeLiquidity The currently in-range liquidity available to the pool
/// @return nextTick The next initialized tick after current global tick
/// @return previousTick The previous initialized tick before (or at) current global tick
function safelyGetStateOfAMM()
external
view
returns (uint160 sqrtPrice, int24 tick, uint16 lastFee, uint8 pluginConfig, uint128 activeLiquidity, int24 nextTick, int24 previousTick);
/// @notice Allows to easily get current reentrancy lock status
/// @dev can be used to prevent read-only reentrancy.
/// This method just returns `globalState.unlocked` value
/// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
function isUnlocked() external view returns (bool unlocked);
// ! IMPORTANT security note: the pool state can be manipulated.
// ! The following methods do not check reentrancy lock themselves.
/// @notice The globalState structure in the pool stores many values but requires only one slot
/// and is exposed as a single method to save gas when accessed externally.
/// @dev **important security note: caller should check `unlocked` flag to prevent read-only reentrancy**
/// @return price The current price of the pool as a sqrt(dToken1/dToken0) Q64.96 value
/// @return 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(price) if the price is on a tick boundary
/// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin
/// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
/// @return communityFee The community fee represented as a percent of all collected fee in thousandths, i.e. 1e-3 (so 100 is 10%)
/// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
function globalState() external view returns (uint160 price, int24 tick, uint16 lastFee, uint8 pluginConfig, uint16 communityFee, bool unlocked);
/// @notice Look up information about a specific tick in the pool
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @param tick The tick to look up
/// @return liquidityTotal The total amount of position liquidity that uses the pool either as tick lower or tick upper
/// @return liquidityDelta How much liquidity changes when the pool price crosses the tick
/// @return prevTick The previous tick in tick list
/// @return nextTick The next tick in tick list
/// @return outerFeeGrowth0Token The fee growth on the other side of the tick from the current tick in token0
/// @return outerFeeGrowth1Token The fee growth on the other side of the tick from the current tick in token1
/// 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 (
uint256 liquidityTotal,
int128 liquidityDelta,
int24 prevTick,
int24 nextTick,
uint256 outerFeeGrowth0Token,
uint256 outerFeeGrowth1Token
);
/// @notice The timestamp of the last sending of tokens to vault/plugin
/// @return The timestamp truncated to 32 bits
function lastFeeTransferTimestamp() external view returns (uint32);
/// @notice The amounts of token0 and token1 that will be sent to the vault
/// @dev Will be sent FEE_TRANSFER_FREQUENCY after communityFeeLastTimestamp
/// @return communityFeePending0 The amount of token0 that will be sent to the vault
/// @return communityFeePending1 The amount of token1 that will be sent to the vault
function getCommunityFeePending() external view returns (uint128 communityFeePending0, uint128 communityFeePending1);
/// @notice The amounts of token0 and token1 that will be sent to the plugin
/// @dev Will be sent FEE_TRANSFER_FREQUENCY after feeLastTransferTimestamp
/// @return pluginFeePending0 The amount of token0 that will be sent to the plugin
/// @return pluginFeePending1 The amount of token1 that will be sent to the plugin
function getPluginFeePending() external view returns (uint128 pluginFeePending0, uint128 pluginFeePending1);
/// @notice Returns the address of currently used plugin
/// @dev The plugin is subject to change
/// @return pluginAddress The address of currently used plugin
function plugin() external view returns (address pluginAddress);
/// @notice The contract to which community fees are transferred
/// @return communityVaultAddress The communityVault address
function communityVault() external view returns (address communityVaultAddress);
/// @notice Returns 256 packed tick initialized boolean values. See TickTree for more information
/// @param wordPosition Index of 256-bits word with ticks
/// @return The 256-bits word with packed ticks info
function tickTable(int16 wordPosition) external view returns (uint256);
/// @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
/// @return The fee growth accumulator for token0
function totalFeeGrowth0Token() 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
/// @return The fee growth accumulator for token1
function totalFeeGrowth1Token() external view returns (uint256);
/// @notice The current pool fee value
/// @dev In case dynamic fee is enabled in the pool, this method will call the plugin to get the current fee.
/// If the plugin implements complex fee logic, this method may return an incorrect value or revert.
/// In this case, see the plugin implementation and related documentation.
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return currentFee The current pool fee value in hundredths of a bip, i.e. 1e-6
function fee() external view returns (uint16 currentFee);
/// @notice The tracked token0 and token1 reserves of pool
/// @dev If at any time the real balance is larger, the excess will be transferred to liquidity providers as additional fee.
/// If the balance exceeds uint128, the excess will be sent to the communityVault.
/// @return reserve0 The last known reserve of token0
/// @return reserve1 The last known reserve of token1
function getReserves() external view returns (uint128 reserve0, uint128 reserve1);
/// @notice Returns the information about a position by the position's key
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @param key The position's key is a packed concatenation of the owner address, bottomTick and topTick indexes
/// @return liquidity The amount of liquidity in the position
/// @return innerFeeGrowth0Token Fee growth of token0 inside the tick range as of the last mint/burn/poke
/// @return innerFeeGrowth1Token Fee growth of token1 inside the tick range as of the last mint/burn/poke
/// @return fees0 The computed amount of token0 owed to the position as of the last mint/burn/poke
/// @return fees1 The computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(
bytes32 key
) external view returns (uint256 liquidity, uint256 innerFeeGrowth0Token, uint256 innerFeeGrowth1Token, uint128 fees0, uint128 fees1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks.
/// Returned value cannot exceed type(uint128).max
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The current in range liquidity
function liquidity() external view returns (uint128);
/// @notice The current tick spacing
/// @dev Ticks can only be initialized by new mints at multiples of this value
/// e.g.: a tickSpacing of 60 means ticks can be initialized every 60th tick, i.e., ..., -120, -60, 0, 60, 120, ...
/// However, tickspacing can be changed after the ticks have been initialized.
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The current tick spacing
function tickSpacing() external view returns (int24);
/// @notice The previous initialized tick before (or at) current global tick
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The previous initialized tick
function prevTickGlobal() external view returns (int24);
/// @notice The next initialized tick after current global tick
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The next initialized tick
function nextTickGlobal() external view returns (int24);
/// @notice The root of tick search tree
/// @dev Each bit corresponds to one node in the second layer of tick tree: '1' if node has at least one active bit.
/// **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The root of tick search tree as bitmap
function tickTreeRoot() external view returns (uint32);
/// @notice The second layer of tick search tree
/// @dev Each bit in node corresponds to one node in the leafs layer (`tickTable`) of tick tree: '1' if leaf has at least one active bit.
/// **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The node of tick search tree second layer
function tickTreeSecondLayer(int16) external view returns (uint256);
}
@cryptoalgebra/integral-core/contracts/interfaces/vault/IAlgebraVaultFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Algebra Vault Factory
/// @notice This contract can be used for automatic vaults creation
/// @dev Version: Algebra Integral
interface IAlgebraVaultFactory {
/// @notice returns address of the community fee vault for the pool
/// @param pool the address of Algebra Integral pool
/// @return communityFeeVault the address of community fee vault
function getVaultForPool(address pool) external view returns (address communityFeeVault);
/// @notice creates the community fee vault for the pool if needed
/// @param pool the address of Algebra Integral pool
/// @return communityFeeVault the address of community fee vault
function createVaultForPool(
address pool,
address creator,
address deployer,
address token0,
address token1
) external returns (address communityFeeVault);
}
@cryptoalgebra/integral-core/contracts/libraries/Constants.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.9.0;
/// @title Contains common constants for Algebra contracts
/// @dev Constants moved to the library, not the base contract, to further emphasize their constant nature
library Constants {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 1 << 96;
uint256 internal constant Q128 = 1 << 128;
uint24 internal constant FEE_DENOMINATOR = 1e6;
uint16 internal constant FLASH_FEE = 0.01e4; // fee for flash loan in hundredths of a bip (0.01%)
uint16 internal constant INIT_DEFAULT_FEE = 0.05e4; // init default fee value in hundredths of a bip (0.05%)
uint16 internal constant MAX_DEFAULT_FEE = 5e4; // max default fee value in hundredths of a bip (5%)
int24 internal constant INIT_DEFAULT_TICK_SPACING = 60;
int24 internal constant MAX_TICK_SPACING = 500;
int24 internal constant MIN_TICK_SPACING = 1;
// the frequency with which the accumulated community fees are sent to the vault
uint32 internal constant FEE_TRANSFER_FREQUENCY = 8 hours;
// max(uint128) / (MAX_TICK - MIN_TICK)
uint128 internal constant MAX_LIQUIDITY_PER_TICK = 191757638537527648490752896198553;
uint16 internal constant MAX_COMMUNITY_FEE = 1e3; // 100%
uint256 internal constant COMMUNITY_FEE_DENOMINATOR = 1e3;
// role that can change settings in pools
bytes32 internal constant POOLS_ADMINISTRATOR_ROLE = keccak256('POOLS_ADMINISTRATOR');
}
@cryptoalgebra/integral-core/contracts/libraries/Plugins.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4 <0.9.0;
import '../interfaces/pool/IAlgebraPoolErrors.sol';
/// @title Contains logic and constants for interacting with the plugin through hooks
/// @dev Allows pool to check which hooks are enabled, as well as control the return selector
library Plugins {
function hasFlag(uint8 pluginConfig, uint256 flag) internal pure returns (bool res) {
assembly {
res := gt(and(pluginConfig, flag), 0)
}
}
function shouldReturn(bytes4 selector, bytes4 expectedSelector) internal pure {
if (selector != expectedSelector) revert IAlgebraPoolErrors.invalidHookResponse(expectedSelector);
}
uint256 internal constant BEFORE_SWAP_FLAG = 1;
uint256 internal constant AFTER_SWAP_FLAG = 1 << 1;
uint256 internal constant BEFORE_POSITION_MODIFY_FLAG = 1 << 2;
uint256 internal constant AFTER_POSITION_MODIFY_FLAG = 1 << 3;
uint256 internal constant BEFORE_FLASH_FLAG = 1 << 4;
uint256 internal constant AFTER_FLASH_FLAG = 1 << 5;
uint256 internal constant AFTER_INIT_FLAG = 1 << 6;
uint256 internal constant DYNAMIC_FEE = 1 << 7;
}
@cryptoalgebra/integral-core/contracts/libraries/SafeTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4 <0.9.0;
import '../interfaces/pool/IAlgebraPoolErrors.sol';
/// @title SafeTransfer
/// @notice Safe ERC20 transfer library that gracefully handles missing return values.
/// @dev Credit to Solmate under MIT license: https://github.com/transmissions11/solmate/blob/ed67feda67b24fdeff8ad1032360f0ee6047ba0a/src/utils/SafeTransferLib.sol
/// @dev Please note that this library does not check if the token has a code! That responsibility is delegated to the caller.
library SafeTransfer {
/// @notice Transfers tokens to a recipient
/// @dev Calls transfer on token contract, errors with transferFailed() if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param amount The amount of the token to transfer
function safeTransfer(address token, address to, uint256 amount) internal {
bool success;
assembly {
let freeMemoryPointer := mload(0x40) // we will need to restore 0x40 slot
mstore(0x00, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // "transfer(address,uint256)" selector
mstore(0x04, and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // append cleaned "to" address
mstore(0x24, amount)
// now we use 0x00 - 0x44 bytes (68), freeMemoryPointer is dirty
success := call(gas(), token, 0, 0, 0x44, 0, 0x20)
success := and(
// set success to true if call isn't reverted and returned exactly 1 (can't just be non-zero data) or nothing
or(and(eq(mload(0), 1), eq(returndatasize(), 32)), iszero(returndatasize())),
success
)
mstore(0x40, freeMemoryPointer) // restore the freeMemoryPointer
}
if (!success) revert IAlgebraPoolErrors.transferFailed();
}
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from" argument.
mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
// We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
success := call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data and token has code.
if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {
success := iszero(or(iszero(extcodesize(token)), returndatasize()))
}
}
require(success, 'TRANSFER_FROM_FAILED');
}
}
@cryptoalgebra/volatility-oracle-plugin/contracts/interfaces/IVolatilityOracle.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Algebra volatility oracle
/// @dev This contract stores timepoints and calculates statistical averages
interface IVolatilityOracle {
/// @notice Returns data belonging to a certain timepoint
/// @param index The index of timepoint in the array
/// @dev There is more convenient function to fetch a timepoint: getTimepoints(). Which requires not an index but seconds
/// @return initialized Whether the timepoint has been initialized and the values are safe to use
/// @return blockTimestamp The timestamp of the timepoint
/// @return tickCumulative The tick multiplied by seconds elapsed for the life of the pool as of the timepoint timestamp
/// @return volatilityCumulative Cumulative standard deviation for the life of the pool as of the timepoint timestamp
/// @return tick The tick at blockTimestamp
/// @return averageTick Time-weighted average tick
/// @return windowStartIndex Index of closest timepoint >= WINDOW seconds ago
function timepoints(
uint256 index
)
external
view
returns (
bool initialized,
uint32 blockTimestamp,
int56 tickCumulative,
uint88 volatilityCumulative,
int24 tick,
int24 averageTick,
uint16 windowStartIndex
);
/// @notice Returns the index of the last timepoint that was written.
/// @return index of the last timepoint written
function timepointIndex() external view returns (uint16);
/// @notice Initialize the plugin externally
/// @dev This function allows to initialize the plugin if it was created after the pool was created
function initialize() external;
/// @notice Returns the timestamp of the last timepoint that was written.
/// @return timestamp of the last timepoint
function lastTimepointTimestamp() external view returns (uint32);
/// @notice Returns information about whether oracle is initialized
/// @return true if oracle is initialized, otherwise false
function isInitialized() external view returns (bool);
/// @dev Reverts if a timepoint at or before the desired timepoint timestamp does not exist.
/// 0 may be passed as `secondsAgo' to return the current cumulative values.
/// If called with a timestamp falling between two timepoints, returns the counterfactual accumulator values
/// at exactly the timestamp between the two timepoints.
/// @dev `volatilityCumulative` values for timestamps after the last timepoint _should not_ be compared because they may differ due to interpolation errors
/// @param secondsAgo The amount of time to look back, in seconds, at which point to return a timepoint
/// @return tickCumulative The cumulative tick since the pool was first initialized, as of `secondsAgo`
/// @return volatilityCumulative The cumulative volatility value since the pool was first initialized, as of `secondsAgo`
function getSingleTimepoint(uint32 secondsAgo) external view returns (int56 tickCumulative, uint88 volatilityCumulative);
/// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`
/// @dev Reverts if `secondsAgos` > oldest timepoint
/// @dev `volatilityCumulative` values for timestamps after the last timepoint _should not_ be compared because they may differ due to interpolation errors
/// @param secondsAgos Each amount of time to look back, in seconds, at which point to return a timepoint
/// @return tickCumulatives The cumulative tick since the pool was first initialized, as of each `secondsAgo`
/// @return volatilityCumulatives The cumulative volatility values since the pool was first initialized, as of each `secondsAgo`
function getTimepoints(
uint32[] memory secondsAgos
) external view returns (int56[] memory tickCumulatives, uint88[] memory volatilityCumulatives);
/// @notice Fills uninitialized timepoints with nonzero value
/// @dev Can be used to reduce the gas cost of future swaps
/// @param startIndex The start index, must be not initialized
/// @param amount of slots to fill, startIndex + amount must be <= type(uint16).max
function prepayTimepointsStorageSlots(uint16 startIndex, uint16 amount) external;
}
@cryptoalgebra/volatility-oracle-plugin/contracts/libraries/VolatilityOracle.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
/// @title VolatilityOracle
/// @notice Provides price and volatility data useful for a wide variety of system designs
/// @dev Instances of stored oracle data, "timepoints", are collected in the oracle array
/// Timepoints are overwritten when the full length of the timepoints array is populated.
/// The most recent timepoint is available by passing 0 to getSingleTimepoint().
library VolatilityOracle {
/// @notice `target` timestamp is older than oldest timepoint
error targetIsTooOld();
/// @notice oracle is initialized already
error volatilityOracleAlreadyInitialized();
uint32 internal constant WINDOW = 1 days;
uint256 private constant UINT16_MODULO = 65536;
struct Timepoint {
bool initialized; // whether or not the timepoint is initialized
uint32 blockTimestamp; // the block timestamp of the timepoint
int56 tickCumulative; // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized
uint88 volatilityCumulative; // the volatility accumulator; overflow after ~34800 years is desired :)
int24 tick; // tick at this blockTimestamp
int24 averageTick; // average tick at this blockTimestamp (for WINDOW seconds)
uint16 windowStartIndex; // closest timepoint lte WINDOW seconds ago (or oldest timepoint), _should be used only from last timepoint_!
}
/// @notice Initialize the timepoints array by writing the first slot. Called once for the lifecycle of the timepoints array
/// @param self The stored timepoints array
/// @param time The time of the oracle initialization, via block.timestamp truncated to uint32
/// @param tick Initial tick
function initialize(Timepoint[UINT16_MODULO] storage self, uint32 time, int24 tick) internal {
Timepoint storage _zero = self[0];
if (_zero.initialized) revert volatilityOracleAlreadyInitialized();
(_zero.initialized, _zero.blockTimestamp, _zero.tick, _zero.averageTick) = (true, time, tick, tick);
}
/// @notice Writes a timepoint to the array
/// @dev Writable at most once per block. `lastIndex` must be tracked externally.
/// @param self The stored timepoints array
/// @param lastIndex The index of the timepoint that was most recently written to the timepoints array
/// @param blockTimestamp The timestamp of the new timepoint
/// @param tick The active tick at the time of the new timepoint
/// @return indexUpdated The new index of the most recently written element in the timepoints array
/// @return oldestIndex The new index of the oldest timepoint
function write(
Timepoint[UINT16_MODULO] storage self,
uint16 lastIndex,
uint32 blockTimestamp,
int24 tick
) internal returns (uint16 indexUpdated, uint16 oldestIndex) {
Timepoint memory last = self[lastIndex];
// early return if we've already written a timepoint this block
if (last.blockTimestamp == blockTimestamp) return (lastIndex, 0);
// get next index considering overflow
unchecked {
indexUpdated = lastIndex + 1;
}
// check if we have overflow in the past
if (self[indexUpdated].initialized) oldestIndex = indexUpdated;
(int24 avgTick, uint16 windowStartIndex) = _getAverageTickCasted(
self,
blockTimestamp,
tick,
lastIndex,
oldestIndex,
last.blockTimestamp,
last.tickCumulative
);
unchecked {
// overflow of indexes is desired
if (windowStartIndex == indexUpdated) windowStartIndex++; // important, since this value can be used to narrow the search
self[indexUpdated] = _createNewTimepoint(last, blockTimestamp, tick, avgTick, windowStartIndex);
if (oldestIndex == indexUpdated) oldestIndex++; // previous oldest index has been overwritten
}
}
/// @dev Reverts if a timepoint at or before the desired timepoint timestamp does not exist.
/// 0 may be passed as `secondsAgo' to return the current cumulative values.
/// If called with a timestamp falling between two timepoints, returns the counterfactual accumulator values
/// at exactly the timestamp between the two timepoints.
/// @dev `volatilityCumulative` values for timestamps after the last timepoint _should not_ be compared because they may differ due to interpolation errors
/// @param self The stored timepoints array
/// @param time The current block timestamp
/// @param secondsAgo The amount of time to look back, in seconds, at which point to return a timepoint
/// @param tick The current tick
/// @param lastIndex The index of the timepoint that was most recently written to the timepoints array
/// @param oldestIndex The index of the oldest timepoint
/// @return targetTimepoint desired timepoint or it's interpolation
function getSingleTimepoint(
Timepoint[UINT16_MODULO] storage self,
uint32 time,
uint32 secondsAgo,
int24 tick,
uint16 lastIndex,
uint16 oldestIndex
) internal view returns (Timepoint memory targetTimepoint) {
unchecked {
uint32 target = time - secondsAgo;
(Timepoint storage beforeOrAt, Timepoint storage atOrAfter, bool samePoint, ) = _getTimepointsAt(
self,
time,
target,
lastIndex,
oldestIndex
);
targetTimepoint = beforeOrAt;
if (target == targetTimepoint.blockTimestamp) return targetTimepoint; // we're at the left boundary
if (samePoint) {
// if target is newer than last timepoint
(int24 avgTick, uint16 windowStartIndex) = _getAverageTickCasted(
self,
target,
tick,
lastIndex,
oldestIndex,
targetTimepoint.blockTimestamp,
targetTimepoint.tickCumulative
);
return _createNewTimepoint(targetTimepoint, target, tick, avgTick, windowStartIndex);
}
(uint32 timestampAfter, int56 tickCumulativeAfter) = (atOrAfter.blockTimestamp, atOrAfter.tickCumulative);
if (target == timestampAfter) return atOrAfter; // we're at the right boundary
// we're in the middle
(uint32 timepointTimeDelta, uint32 targetDelta) = (
timestampAfter - targetTimepoint.blockTimestamp,
target - targetTimepoint.blockTimestamp
);
targetTimepoint.tickCumulative +=
((tickCumulativeAfter - targetTimepoint.tickCumulative) / int56(uint56(timepointTimeDelta))) *
int56(uint56(targetDelta));
targetTimepoint.volatilityCumulative +=
((atOrAfter.volatilityCumulative - targetTimepoint.volatilityCumulative) / timepointTimeDelta) *
targetDelta;
}
}
/// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`
/// @dev Reverts if `secondsAgos` > oldest timepoint
/// @dev `volatilityCumulative` values for timestamps after the last timepoint _should not_ be compared because they may differ due to interpolation errors
/// @param self The stored timepoints array
/// @param currentTime The current block.timestamp
/// @param secondsAgos Each amount of time to look back, in seconds, at which point to return a timepoint
/// @param tick The current tick
/// @param lastIndex The index of the timepoint that was most recently written to the timepoints array
/// @return tickCumulatives The cumulative time-weighted tick since the pool was first initialized, as of each `secondsAgo`
/// @return volatilityCumulatives The cumulative volatility values since the pool was first initialized, as of each `secondsAgo`
function getTimepoints(
Timepoint[UINT16_MODULO] storage self,
uint32 currentTime,
uint32[] memory secondsAgos,
int24 tick,
uint16 lastIndex
) internal view returns (int56[] memory tickCumulatives, uint88[] memory volatilityCumulatives) {
uint256 secondsLength = secondsAgos.length;
tickCumulatives = new int56[](secondsLength);
volatilityCumulatives = new uint88[](secondsLength);
uint16 oldestIndex = getOldestIndex(self, lastIndex);
Timepoint memory current;
unchecked {
for (uint256 i; i < secondsLength; ++i) {
current = getSingleTimepoint(self, currentTime, secondsAgos[i], tick, lastIndex, oldestIndex);
(tickCumulatives[i], volatilityCumulatives[i]) = (current.tickCumulative, current.volatilityCumulative);
}
}
}
/// @notice Returns the index of the oldest timepoint
/// @param self The stored timepoints array
/// @param lastIndex The index of the timepoint that was most recently written to the timepoints array
/// @return oldestIndex The index of the oldest timepoint
function getOldestIndex(Timepoint[UINT16_MODULO] storage self, uint16 lastIndex) internal view returns (uint16 oldestIndex) {
unchecked {
uint16 nextIndex = lastIndex + 1; // considering overflow
if (self[nextIndex].initialized) oldestIndex = nextIndex; // check if we have overflow in the past
}
}
/// @notice Returns average volatility in the range from currentTime-WINDOW to currentTime
/// @param self The stored timepoints array
/// @param currentTime The current block.timestamp
/// @param tick The current tick
/// @param lastIndex The index of the timepoint that was most recently written to the timepoints array
/// @param oldestIndex The index of the oldest timepoint
/// @return volatilityAverage The average volatility in the recent range
function getAverageVolatility(
Timepoint[UINT16_MODULO] storage self,
uint32 currentTime,
int24 tick,
uint16 lastIndex,
uint16 oldestIndex
) internal view returns (uint88 volatilityAverage) {
unchecked {
Timepoint storage lastTimepoint = self[lastIndex];
bool timeAtLastTimepoint = lastTimepoint.blockTimestamp == currentTime;
uint88 lastCumulativeVolatility = lastTimepoint.volatilityCumulative;
uint16 windowStartIndex = lastTimepoint.windowStartIndex; // index of timepoint before of at lastTimepoint.blockTimestamp - WINDOW
if (!timeAtLastTimepoint) {
lastCumulativeVolatility = _getVolatilityCumulativeAt(self, currentTime, 0, tick, lastIndex, oldestIndex);
}
uint32 oldestTimestamp = self[oldestIndex].blockTimestamp;
if (_lteConsideringOverflow(oldestTimestamp, currentTime - WINDOW, currentTime)) {
// oldest timepoint is earlier than 24 hours ago
uint88 cumulativeVolatilityAtStart;
if (timeAtLastTimepoint) {
// interpolate cumulative volatility to avoid search. Since the last timepoint has _just_ been written, we know for sure
// that the start of the window is between windowStartIndex and windowStartIndex + 1
(oldestTimestamp, cumulativeVolatilityAtStart) = (
self[windowStartIndex].blockTimestamp,
self[windowStartIndex].volatilityCumulative
);
uint32 timeDeltaBetweenPoints = self[windowStartIndex + 1].blockTimestamp - oldestTimestamp;
cumulativeVolatilityAtStart +=
((self[windowStartIndex + 1].volatilityCumulative - cumulativeVolatilityAtStart) * (currentTime - WINDOW - oldestTimestamp)) /
timeDeltaBetweenPoints;
} else {
cumulativeVolatilityAtStart = _getVolatilityCumulativeAt(self, currentTime, WINDOW, tick, lastIndex, oldestIndex);
}
return ((lastCumulativeVolatility - cumulativeVolatilityAtStart) / WINDOW); // sample is big enough to ignore bias of variance
} else if (currentTime != oldestTimestamp) {
// recorded timepoints are not enough, so we will extrapolate
uint88 _oldestVolatilityCumulative = self[oldestIndex].volatilityCumulative;
uint32 unbiasedDenominator = currentTime - oldestTimestamp;
if (unbiasedDenominator > 1) unbiasedDenominator--; // Bessel's correction for "small" sample
return ((lastCumulativeVolatility - _oldestVolatilityCumulative) / unbiasedDenominator);
}
}
}
// ##### further functions are private to the library, but some are made internal for fuzzy testing #####
/// @notice Transforms a previous timepoint into a new timepoint, given the passage of time and the current tick and liquidity values
/// @dev blockTimestamp _must_ be chronologically equal to or greater than last.blockTimestamp, safe for 0 or 1 overflows
/// @dev The function changes the structure given to the input, and does not create a new one
/// @param last The specified timepoint to be used in creation of new timepoint
/// @param blockTimestamp The timestamp of the new timepoint
/// @param tick The active tick at the time of the new timepoint
/// @param averageTick The average tick at the time of the new timepoint
/// @param windowStartIndex The index of closest timepoint >= WINDOW seconds ago
/// @return Timepoint The newly populated timepoint
function _createNewTimepoint(
Timepoint memory last,
uint32 blockTimestamp,
int24 tick,
int24 averageTick,
uint16 windowStartIndex
) internal pure returns (Timepoint memory) {
unchecked {
uint32 delta = blockTimestamp - last.blockTimestamp; // overflow is desired
// We don't create a new structure in memory to save gas. Therefore, the function changes the old structure
last.initialized = true;
last.blockTimestamp = blockTimestamp;
last.tickCumulative += int56(tick) * int56(uint56(delta));
last.volatilityCumulative += uint88(_volatilityOnRange(int256(uint256(delta)), tick, tick, last.averageTick, averageTick)); // always fits 88 bits
last.tick = tick;
last.averageTick = averageTick;
last.windowStartIndex = windowStartIndex;
return last;
}
}
/// @notice Calculates volatility between two sequential timepoints with resampling to 1 sec frequency
/// @param dt Timedelta between timepoints, must be within uint32 range
/// @param tick0 The tick after the left timepoint, must be within int24 range
/// @param tick1 The tick at the right timepoint, must be within int24 range
/// @param avgTick0 The average tick at the left timepoint, must be within int24 range
/// @param avgTick1 The average tick at the right timepoint, must be within int24 range
/// @return volatility The volatility between two sequential timepoints
/// If the requirements for the parameters are met, it always fits 88 bits
function _volatilityOnRange(
int256 dt,
int256 tick0,
int256 tick1,
int256 avgTick0,
int256 avgTick1
) internal pure returns (uint256 volatility) {
// On the time interval from the previous timepoint to the current
// we can represent tick and average tick change as two straight lines:
// tick = k*t + b, where k and b are some constants
// avgTick = p*t + q, where p and q are some constants
// we want to get sum of (tick(t) - avgTick(t))^2 for every t in the interval (0; dt]
// so: (tick(t) - avgTick(t))^2 = ((k*t + b) - (p*t + q))^2 = (k-p)^2 * t^2 + 2(k-p)(b-q)t + (b-q)^2
// since everything except t is a constant, we need to use progressions for t and t^2:
// sum(t) for t from 1 to dt = dt*(dt + 1)/2 = sumOfSequence
// sum(t^2) for t from 1 to dt = dt*(dt+1)*(2dt + 1)/6 = sumOfSquares
// so result will be: (k-p)^2 * sumOfSquares + 2(k-p)(b-q)*sumOfSequence + dt*(b-q)^2
unchecked {
int256 k = (tick1 - tick0) - (avgTick1 - avgTick0); // (k - p)*dt
int256 b = (tick0 - avgTick0) * dt; // (b - q)*dt
int256 sumOfSequence = dt * (dt + 1); // sumOfSequence * 2
int256 sumOfSquares = sumOfSequence * (2 * dt + 1); // sumOfSquares * 6
volatility = uint256((k ** 2 * sumOfSquares + 6 * b * k * sumOfSequence + 6 * dt * b ** 2) / (6 * dt ** 2));
}
}
/// @notice Calculates average tick for WINDOW seconds at the moment of `time`
/// @dev Guaranteed that the result is within the bounds of int24
/// @return avgTick The average tick
/// @return windowStartIndex The index of closest timepoint <= WINDOW seconds ago
function _getAverageTickCasted(
Timepoint[UINT16_MODULO] storage self,
uint32 time,
int24 tick,
uint16 lastIndex,
uint16 oldestIndex,
uint32 lastTimestamp,
int56 lastTickCumulative
) internal view returns (int24 avgTick, uint16 windowStartIndex) {
(int256 _avgTick, uint256 _windowStartIndex) = _getAverageTick(
self,
time,
tick,
lastIndex,
oldestIndex,
lastTimestamp,
lastTickCumulative
);
unchecked {
(avgTick, windowStartIndex) = (int24(_avgTick), uint16(_windowStartIndex)); // overflow in uint16(_windowStartIndex) is desired
}
}
/// @notice Calculates average tick for WINDOW seconds at the moment of `currentTime`
/// @dev Guaranteed that the result is within the bounds of int24, but result is not casted
/// @return avgTick int256 for fuzzy tests
/// @return windowStartIndex The index of closest timepoint <= WINDOW seconds ago
function _getAverageTick(
Timepoint[UINT16_MODULO] storage self,
uint32 currentTime,
int24 tick,
uint16 lastIndex,
uint16 oldestIndex,
uint32 lastTimestamp,
int56 lastTickCumulative
) internal view returns (int256 avgTick, uint256 windowStartIndex) {
(uint32 oldestTimestamp, int56 oldestTickCumulative) = (self[oldestIndex].blockTimestamp, self[oldestIndex].tickCumulative);
unchecked {
int56 currentTickCumulative = lastTickCumulative + int56(tick) * int56(uint56(currentTime - lastTimestamp)); // update with new data
if (!_lteConsideringOverflow(oldestTimestamp, currentTime - WINDOW, currentTime)) {
// if oldest is newer than WINDOW ago
if (currentTime == oldestTimestamp) return (tick, oldestIndex);
return ((currentTickCumulative - oldestTickCumulative) / int56(uint56(currentTime - oldestTimestamp)), oldestIndex);
}
if (_lteConsideringOverflow(lastTimestamp, currentTime - WINDOW, currentTime)) {
// if last timepoint is older or equal than WINDOW ago
return (tick, lastIndex);
} else {
int56 tickCumulativeAtStart;
(tickCumulativeAtStart, windowStartIndex) = _getTickCumulativeAt(self, currentTime, WINDOW, tick, lastIndex, oldestIndex);
// current-WINDOW last current
// _________*____________*_______*_
// ||||||||||||||||||||||
avgTick = (currentTickCumulative - tickCumulativeAtStart) / int56(uint56(WINDOW));
}
}
}
/// @notice comparator for 32-bit timestamps
/// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to currentTime
/// @param a A comparison timestamp from which to determine the relative position of `currentTime`
/// @param b From which to determine the relative position of `currentTime`
/// @param currentTime A timestamp truncated to 32 bits
/// @return res Whether `a` is chronologically <= `b`
function _lteConsideringOverflow(uint32 a, uint32 b, uint32 currentTime) internal pure returns (bool res) {
res = a > currentTime;
if (res == b > currentTime) res = a <= b; // if both are on the same side
}
/// @notice Calculates cumulative volatility at the moment of `time` - `secondsAgo`
/// @dev More optimal than via `getSingleTimepoint`
/// @return volatilityCumulative The cumulative volatility
function _getVolatilityCumulativeAt(
Timepoint[UINT16_MODULO] storage self,
uint32 time,
uint32 secondsAgo,
int24 tick,
uint16 lastIndex,
uint16 oldestIndex
) internal view returns (uint88 volatilityCumulative) {
unchecked {
uint32 target = time - secondsAgo;
(Timepoint storage beforeOrAt, Timepoint storage atOrAfter, bool samePoint, ) = _getTimepointsAt(
self,
time,
target,
lastIndex,
oldestIndex
);
(uint32 timestampBefore, uint88 volatilityCumulativeBefore) = (beforeOrAt.blockTimestamp, beforeOrAt.volatilityCumulative);
if (target == timestampBefore) return volatilityCumulativeBefore; // we're at the left boundary
if (samePoint) {
// since target != beforeOrAt.blockTimestamp, `samePoint` means that target is newer than last timepoint
(int24 avgTick, ) = _getAverageTickCasted(self, target, tick, lastIndex, oldestIndex, timestampBefore, beforeOrAt.tickCumulative);
return (volatilityCumulativeBefore +
uint88(_volatilityOnRange(int256(uint256(target - timestampBefore)), tick, tick, beforeOrAt.averageTick, avgTick)));
}
(uint32 timestampAfter, uint88 volatilityCumulativeAfter) = (atOrAfter.blockTimestamp, atOrAfter.volatilityCumulative);
if (target == timestampAfter) return volatilityCumulativeAfter; // we're at the right boundary
// we're in the middle
(uint32 timepointTimeDelta, uint32 targetDelta) = (timestampAfter - timestampBefore, target - timestampBefore);
return volatilityCumulativeBefore + ((volatilityCumulativeAfter - volatilityCumulativeBefore) / timepointTimeDelta) * targetDelta;
}
}
/// @notice Calculates cumulative tick at the moment of `time` - `secondsAgo`
/// @dev More optimal than via `getSingleTimepoint`
/// @return tickCumulative The cumulative tick
/// @return indexBeforeOrAt The index of closest timepoint before or at the moment of `time` - `secondsAgo`
function _getTickCumulativeAt(
Timepoint[UINT16_MODULO] storage self,
uint32 time,
uint32 secondsAgo,
int24 tick,
uint16 lastIndex,
uint16 oldestIndex
) internal view returns (int56 tickCumulative, uint256 indexBeforeOrAt) {
unchecked {
uint32 target = time - secondsAgo;
(Timepoint storage beforeOrAt, Timepoint storage atOrAfter, bool samePoint, uint256 _indexBeforeOrAt) = _getTimepointsAt(
self,
time,
target,
lastIndex,
oldestIndex
);
(uint32 timestampBefore, int56 tickCumulativeBefore) = (beforeOrAt.blockTimestamp, beforeOrAt.tickCumulative);
if (target == timestampBefore) return (tickCumulativeBefore, _indexBeforeOrAt); // we're at the left boundary
// since target != timestampBefore, `samePoint` means that target is newer than last timepoint
if (samePoint) return ((tickCumulativeBefore + int56(tick) * int56(uint56(target - timestampBefore))), _indexBeforeOrAt); // if target is newer than last timepoint
(uint32 timestampAfter, int56 tickCumulativeAfter) = (atOrAfter.blockTimestamp, atOrAfter.tickCumulative);
if (target == timestampAfter) return (tickCumulativeAfter, uint16(_indexBeforeOrAt + 1)); // we're at the right boundary
// we're in the middle
(uint32 timepointTimeDelta, uint32 targetDelta) = (timestampAfter - timestampBefore, target - timestampBefore);
return (
tickCumulativeBefore +
((tickCumulativeAfter - tickCumulativeBefore) / int56(uint56(timepointTimeDelta))) *
int56(uint56(targetDelta)),
_indexBeforeOrAt
);
}
}
/// @notice Returns closest timepoint or timepoints to the moment of `target`
/// @return beforeOrAt The timepoint recorded before, or at, the target
/// @return atOrAfter The timepoint recorded at, or after, the target
/// @return samePoint Are `beforeOrAt` and `atOrAfter` the same or not
/// @return indexBeforeOrAt The index of closest timepoint before or at the moment of `target`
function _getTimepointsAt(
Timepoint[UINT16_MODULO] storage self,
uint32 currentTime,
uint32 target,
uint16 lastIndex,
uint16 oldestIndex
) private view returns (Timepoint storage beforeOrAt, Timepoint storage atOrAfter, bool samePoint, uint256 indexBeforeOrAt) {
Timepoint storage lastTimepoint = self[lastIndex];
uint32 lastTimepointTimestamp = lastTimepoint.blockTimestamp;
uint16 windowStartIndex = lastTimepoint.windowStartIndex;
// if target is newer than last timepoint
if (target == currentTime || _lteConsideringOverflow(lastTimepointTimestamp, target, currentTime)) {
return (lastTimepoint, lastTimepoint, true, lastIndex);
}
bool useHeuristic;
unchecked {
if (lastTimepointTimestamp - target <= WINDOW) {
// We can limit the scope of the search. It is safe because when the array overflows,
// `windowsStartIndex` cannot point to the overwritten timepoint (check at `write(...)`)
oldestIndex = windowStartIndex;
useHeuristic = target == currentTime - WINDOW; // heuristic will optimize search for timepoints close to `currentTime - WINDOW`
}
uint32 oldestTimestamp = self[oldestIndex].blockTimestamp;
if (!_lteConsideringOverflow(oldestTimestamp, target, currentTime)) revert targetIsTooOld();
if (oldestTimestamp == target) return (self[oldestIndex], self[oldestIndex], true, oldestIndex);
// no need to search if we already know the answer
if (lastIndex == oldestIndex + 1) return (self[oldestIndex], lastTimepoint, false, oldestIndex);
}
(beforeOrAt, atOrAfter, indexBeforeOrAt) = _binarySearch(self, currentTime, target, lastIndex, oldestIndex, useHeuristic);
return (beforeOrAt, atOrAfter, false, indexBeforeOrAt);
}
/// @notice Fetches the timepoints beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied.
/// The result may be the same timepoint, or adjacent timepoints.
/// @dev The answer must be older than the most recent timepoint and younger, or the same age as, the oldest timepoint
/// @param self The stored timepoints array
/// @param currentTime The current block.timestamp
/// @param target The timestamp at which the timepoint should be
/// @param upperIndex The index of the upper border of search range
/// @param lowerIndex The index of the lower border of search range
/// @param withHeuristic Use heuristic for first guess or not (optimize for targets close to `lowerIndex`)
/// @return beforeOrAt The timepoint recorded before, or at, the target
/// @return atOrAfter The timepoint recorded at, or after, the target
function _binarySearch(
Timepoint[UINT16_MODULO] storage self,
uint32 currentTime,
uint32 target,
uint16 upperIndex,
uint16 lowerIndex,
bool withHeuristic
) private view returns (Timepoint storage beforeOrAt, Timepoint storage atOrAfter, uint256 indexBeforeOrAt) {
unchecked {
uint256 left = lowerIndex; // oldest timepoint
uint256 right = upperIndex < lowerIndex ? upperIndex + UINT16_MODULO : upperIndex; // newest timepoint considering one index overflow
(beforeOrAt, atOrAfter, indexBeforeOrAt) = _binarySearchInternal(self, currentTime, target, left, right, withHeuristic);
}
}
function _binarySearchInternal(
Timepoint[UINT16_MODULO] storage self,
uint32 currentTime,
uint32 target,
uint256 left,
uint256 right,
bool withHeuristic
) private view returns (Timepoint storage beforeOrAt, Timepoint storage atOrAfter, uint256 indexBeforeOrAt) {
unchecked {
if (withHeuristic && right - left > 2) {
indexBeforeOrAt = left + 1; // heuristic for first guess
} else {
indexBeforeOrAt = (left + right) >> 1; // "middle" point between the boundaries
}
beforeOrAt = self[uint16(indexBeforeOrAt)]; // checking the "middle" point between the boundaries
atOrAfter = beforeOrAt; // to suppress compiler warning; will be overridden
bool firstIteration = true;
do {
(bool initializedBefore, uint32 timestampBefore) = (beforeOrAt.initialized, beforeOrAt.blockTimestamp);
if (initializedBefore) {
if (_lteConsideringOverflow(timestampBefore, target, currentTime)) {
// is current point before or at `target`?
atOrAfter = self[uint16(indexBeforeOrAt + 1)]; // checking the next point after "middle"
(bool initializedAfter, uint32 timestampAfter) = (atOrAfter.initialized, atOrAfter.blockTimestamp);
if (initializedAfter) {
if (_lteConsideringOverflow(target, timestampAfter, currentTime)) {
// is the "next" point after or at `target`?
return (beforeOrAt, atOrAfter, indexBeforeOrAt); // the only fully correct way to finish
}
left = indexBeforeOrAt + 1; // "next" point is before the `target`, so looking in the right half
} else {
// beforeOrAt is initialized and <= target, and next timepoint is uninitialized
// should be impossible if initial boundaries and `target` are correct
return (beforeOrAt, beforeOrAt, indexBeforeOrAt);
}
} else {
right = indexBeforeOrAt - 1; // current point is after the `target`, so looking in the left half
}
} else {
// we've landed on an uninitialized timepoint, keep searching higher
// should be impossible if initial boundaries and `target` are correct
left = indexBeforeOrAt + 1;
}
// use heuristic if looking in the right half after first iteration
bool useHeuristic = firstIteration && withHeuristic && left == indexBeforeOrAt + 1;
if (useHeuristic && right - left > 16) {
indexBeforeOrAt = left + 8;
} else {
indexBeforeOrAt = (left + right) >> 1; // calculating the new "middle" point index after updating the bounds
}
beforeOrAt = self[uint16(indexBeforeOrAt)]; // update the "middle" point pointer
firstIteration = false;
} while (true);
}
}
}
@cryptoalgebra/volatility-oracle-plugin/contracts/libraries/VolatilityOracleStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import './VolatilityOracle.sol';
/// @dev Shared namespaced storage for VolatilityOracle plugin (used by connector + implementation).
library VolatilityOracleStorage {
uint256 internal constant UINT16_MODULO = 65536;
/// @dev keccak256(abi.encode(uint256(keccak256("erc7201:algebra.storage.volatilityoracle")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant STORAGE_SLOT = 0x4cc5c36a434034246042af122c958f40937cad4aaa0154d3b81e721d7b524c00;
struct Layout {
uint16 timepointIndex;
uint32 lastTimepointTimestamp;
bool isInitialized;
VolatilityOracle.Timepoint[UINT16_MODULO] timepoints;
}
function layout() internal pure returns (Layout storage l) {
bytes32 position = STORAGE_SLOT;
assembly {
l.slot := position
}
}
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (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 Internal function that returns the initialized version. Returns `_initialized`
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Internal function that returns the initialized version. Returns `_initializing`
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
@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);
}
}
}
contracts/interfaces/mevx/IMevxExecutor.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
interface IMevxExecutor {
function executeRoute(bytes calldata encodedRoute, address[] memory pools, uint256 amountIn, address profitToken, address profitRecipient) external;
}
contracts/interfaces/mevx/IMevxPlugin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @title IMevxPlugin
interface IMevxPlugin {
/// @notice Emitted when the configuration ID for profit distribution is updated
event ConfigIdSet(bytes32 oldConfigId, bytes32 newConfigId);
/// @notice Emitted when the profit distributor address is updated
event ProfitDistributorSet(address oldProfitDistributor, address newProfitDistributor);
/// @notice Emitted when the MEVX executor address is updated
event MevxExecutorSet(address oldMevxExecutor, address newMevxExecutor);
/// @notice Emitted when the MEVX router address is updated
event MevxRouterSet(address oldMevxRouter, address newMevxRouter);
/// @notice Emitted when the minimum gas required before entering the MEVX after-swap path is updated
event MinGasLeftSet(uint256 oldMinGasLeft, uint256 newMinGasLeft);
/// @notice Emitted when the gas budget used for MEVX external calls is updated
event CallGasBudgetSet(uint256 oldCallGasBudget, uint256 newCallGasBudget);
/// @notice Returns the current MEVX router address
function getMevxRouter() external view returns (address);
/// @notice Returns the current MEVX executor address
function getMevxExecutor() external view returns (address);
/// @notice Returns the current profit distributor address
function getProfitDistributor() external view returns (address);
/// @notice Returns the current configuration ID for profit distribution
function getConfigId() external view returns (bytes32);
/// @notice Returns the minimum gas required before entering the MEVX after-swap path
function getMinGasLeft() external view returns (uint256);
/// @notice Returns the gas budget used for MEVX external calls
function getCallGasBudget() external view returns (uint256);
/// @notice Updates the configuration ID for profit distribution
function setConfigId(bytes32 configId) external;
/// @notice Updates the profit distributor address
function setProfitDistributor(address profitDistributor) external;
/// @notice Updates the MEVX executor address
function setMevxExecutor(address mevxExecutor) external;
/// @notice Updates the MEVX router address
function setMevxRouter(address mevxRouter) external;
/// @notice Updates the minimum gas required before entering the MEVX after-swap path
function setMinGasLeft(uint256 minGasLeft) external;
/// @notice Updates the gas budget used for MEVX external calls
function setCallGasBudget(uint256 callGasBudget) external;
}
contracts/interfaces/mevx/IMevxRouter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
interface IMevxRouter {
function initializePool(bytes32 poolId, uint16 poolType, bytes memory data) external;
function initializePoolExternally(bytes32 poolId, uint16 poolType, bytes memory data) external;
function initialArbCheck(bytes32 poolId, bool zeroToOne) external returns (bool isArbPossible, bytes16 arbData);
function constructArbitrageRoute(
bytes32 poolId,
bool zeroToOne,
bytes16 arbData,
int256 amount0,
int256 amount1
) external returns (bool isArbPossible, address profitToken, address[] memory pools, uint256 optimalAmountIn, bytes memory encodedRoute);
}
contracts/interfaces/mevx/IProfitDistributor.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
interface IProfitDistributor {
struct ProfitShareConfig {
address[] recipients;
uint256[] shares;
}
function distributeProfit(bytes32 configId, address token) external;
}
contracts/interfaces/plugins/IAntiSniperConnector.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the AntiSniperConnector
/// @notice Provides anti-sniper protection with decaying fees for new token launches
interface IAntiSniperConnector {
/// @notice Configuration for anti-sniper fee mechanism
/// @dev Packed into single storage slot (32 bytes). Set startingFee = 0 to disable.
struct AntiSniperConfig {
address feeReceiver; // 20 bytes - receives anti-sniper fees
uint32 period; // 4 bytes - decay duration (5 min - 1 day)
uint24 startingFee; // 3 bytes - initial fee (max 90%), 0 = disabled
bool disabledPriorStart; // 1 byte - block swaps before start?
uint16 easeIn; // 2 bytes - curve exponent a in thousandths (1000 - 5000), 0 = linear
uint16 easeOut; // 2 bytes - curve exponent b in thousandths (1000 - 5000), 0 = linear
}
/// @notice Emitted when anti-sniper configuration is updated
/// @param config The new configuration
event AntiSniperConfigured(AntiSniperConfig config);
/// @notice Emitted when start timestamp is set
/// @param startTimestamp The timestamp when anti-sniper fees begin
event StartTimestampSet(uint64 startTimestamp);
/// @notice Emitted when an address exemption status changes
/// @param account The address whose status changed
/// @param exempt Whether the address is now exempt
event ExemptionUpdated(address indexed account, bool exempt);
/// @notice Returns the current anti-sniper configuration
/// @return config The current configuration
function antiSniperConfig() external view returns (AntiSniperConfig memory config);
/// @notice Returns the timestamp when anti-sniper fees begin
/// @return The start timestamp
function startTimestamp() external view returns (uint64);
/// @notice Checks if an address is exempt from anti-sniper fees
/// @param account The address to check
/// @return Whether the address is exempt
function isExemptFromAntiSniper(address account) external view returns (bool);
/// @notice Sets the anti-sniper configuration
/// @param config The new configuration
/// @dev Can only change full config before trading starts; after start only feeReceiver
function setAntiSniperConfig(AntiSniperConfig calldata config) external;
/// @notice Sets the timestamp when anti-sniper fees begin
/// @param timestamp Must be in the future
function setStartTimestamp(uint64 timestamp) external;
/// @notice Sets exemption status for an address
/// @param account The address to update
/// @param exempt Whether to exempt the address
function setExemption(address account, bool exempt) external;
}
contracts/interfaces/plugins/INamiFeeOverride.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the fee override module
/// @notice Per-direction fee overrides written by the fee keeper, bounded on every swap and expiring on their own
/// @dev The fee for a direction is the base fee plus that direction's premium, replaced by a live override that is
/// never below it less the pool's maxDiscountBps, decaying back to it over decayWindow after expiry, and clamped
/// to [floor, cap]
interface INamiFeeOverride {
/// @notice Per-pool bounds and premiums, set by the plugin manager
/// @dev cap == 0 means the pool is not configured and charges its Algebra fee untouched. maxDiscountBps is how far
/// below the side fee an override may price a direction, in bps of that fee, 0 means never below it
struct FeeBounds {
uint16 floor;
uint16 cap;
uint16 premium0For1;
uint16 premium1For0;
uint32 decayWindow;
uint16 maxDiscountBps;
}
/// @notice The live override, a side of 0 leaves that direction on its base fee
struct FeeOverride {
uint16 fee0For1;
uint16 fee1For0;
uint40 expiresAt;
}
error InvalidBounds();
error BoundsNotSet();
error FeeAboveCap();
error FeeBelowFloor();
error InvalidTtl();
error EmptyOverride();
event FeeBoundsSet(FeeBounds bounds);
event FeeOverrideSet(uint16 fee0For1, uint16 fee1For0, uint40 expiresAt);
event FeeOverrideCleared();
/// @notice Cheapest floor a pool may be configured with, in pips
function MIN_POOL_FEE() external view returns (uint16);
/// @notice Longest an override can live
function MAX_TTL() external view returns (uint32);
/// @notice Longest decay back to the base fee after an override expires
function MAX_DECAY_WINDOW() external view returns (uint32);
/// @notice Largest discount a pool may allow below its side fee, in bps
function MAX_DISCOUNT_BPS() external view returns (uint16);
/// @notice Returns the pool's bounds and premiums
function feeBounds() external view returns (FeeBounds memory);
/// @notice Returns the live override, expired or not
function feeOverride() external view returns (FeeOverride memory);
/// @notice The fee a swap in the given direction pays right now, before the Mev-X executor bypass
function swapFee(bool zeroToOne) external view returns (uint16);
/// @notice Sets the pool's bounds and premiums. A live override is not touched, the swap path clamps it
function setFeeBounds(FeeBounds calldata bounds) external;
/// @notice Replaces each non-zero side's fee until now + ttl, then decays it back over decayWindow
/// @dev Every call restates both sides and renews the expiry, so an unchanged write keeps the override alive
function setFeeOverride(uint16 fee0For1, uint16 fee1For0, uint32 ttl) external;
/// @notice Removes the override at once, both sides return to their base fee on the next swap
function clearFeeOverride() external;
}
contracts/interfaces/plugins/INamiFeeSource.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
/// @title The interface for a pool fee source
/// @notice Names the segment of time a moment falls in, so the pool can charge the fee its admin assigned to
/// that segment. A segment is a small id the source defines, such as closed, overnight or session
/// @dev Must be a cheap pure or view function, it runs on every swap. When the fee should move smoothly
/// between two segments, for example an opening spike decaying into the session, the source returns both ids
/// and how far along it is in basis points, and the pool blends the two fees. Outside such a transition
/// nextId equals id and blendBps is 0
interface INamiFeeSource {
function segmentAt(uint256 timestamp) external view returns (uint8 id, uint8 nextId, uint16 blendBps);
/// @notice How many segment ids this source can return, ids run from 0 to segmentCount - 1
function segmentCount() external view returns (uint8);
}
contracts/interfaces/plugins/INamiFeeSourceConsumer.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
/// @title The interface for the plugin's fee source link
/// @notice An optional external fee source, such as a market session calendar, read on every swap. The source
/// names the current time segment and the plugin charges the fee the admin assigned to it, blending two fees
/// when the source says it is between segments. A source call that fails reverts the swap, so a swapper can
/// never starve the call to get a cheaper fee, and the config role switches a broken source off
interface INamiFeeSourceConsumer {
error InvalidFeeSource();
error InvalidSegmentFees();
event FeeSourceSet(address indexed source);
event FeeSourceEnabled(bool enabled);
event SegmentFeesSet(uint16[16] fees);
/// @notice Most segments a source may define, one fee each packed in one word
function MAX_SEGMENTS() external view returns (uint8);
/// @notice Returns the source and whether it is enabled
function feeSource() external view returns (address source, bool enabled);
/// @notice The fee assigned to each segment id, 0 means the pool's own base fee
function segmentFees() external view returns (uint16[16] memory);
/// @notice Sets the source. Clears the segment fees, since ids mean different things on another source
function setFeeSource(address source) external;
/// @notice Assigns a fee per segment id of the current source, 0 falls back to the pool's base fee, any other
/// value must be at least MIN_POOL_FEE and sit on an id the source can return
function setSegmentFees(uint16[16] calldata fees) external;
/// @notice Switches the source on or off. Enabling probes the source once and fails if it does not answer
function setFeeSourceEnabled(bool enabled) external;
}
contracts/libraries/AntiSniperStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../interfaces/plugins/IAntiSniperConnector.sol';
/// @title AntiSniperStorage
/// @dev Shared namespaced storage for AntiSniper plugin (used by connector + implementation)
library AntiSniperStorage {
/// @dev keccak256(abi.encode(uint256(keccak256("erc7201:algebra.storage.antisniper")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant NAMESPACE = 0x357b3a127c4f79e0ebf0d5870644df9091bce82e8475ae045079b03838a13b00;
struct Layout {
IAntiSniperConnector.AntiSniperConfig config;
uint64 startTimestamp;
mapping(address => bool) exemptions;
}
function layout() internal pure returns (Layout storage l) {
bytes32 position = NAMESPACE;
assembly {
l.slot := position
}
}
}
contracts/libraries/FeeOverrideStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
/// @dev Namespaced storage for the fee override module. The first slot holds bounds, premiums, the live override,
/// the discount allowance and the source flag. The source address and the fee per segment follow in their own
/// slots, read only when a source is enabled. Later slices append fields after them and never reorder these.
library FeeOverrideStorage {
/// @dev keccak256(abi.encode(uint256(keccak256("erc7201:nami.storage.feeoverride")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant NAMESPACE = 0x4e6a83909802af262770f859c245d2a01fddbd871c0bec861e01a093143bd600;
struct Layout {
// slot 0, 192 bits
uint16 floor;
uint16 cap;
uint16 premium0For1;
uint16 premium1For0;
uint32 decayWindow;
uint16 fee0For1;
uint16 fee1For0;
uint40 expiresAt;
bool sourceEnabled;
uint16 maxDiscountBps;
// slot 1, read only when the source is enabled
address source;
// slot 2, sixteen fees of 16 bits, one per segment id, 0 means the pool's base fee
uint256 segmentFees;
}
function layout() internal pure returns (Layout storage l) {
bytes32 position = NAMESPACE;
assembly {
l.slot := position
}
}
}
contracts/libraries/MevxStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @dev Shared namespaced storage for Mevx plugin (used by connector + implementation).
library MevxStorage {
/// @dev keccak256(abi.encode(uint256(keccak256("erc7201:algebra.storage.mevx")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant NAMESPACE = 0x0265d00335a0dde512278a67fe4cbfe91190506046edc3e7f5f678ec695c6500;
struct Layout {
address mevxRouter;
address mevxExecutor;
address mevxProfitDistributor;
bytes32 mevxConfigId;
uint256 minGasLeft;
uint256 callGasBudget;
}
function layout() internal pure returns (Layout storage l) {
bytes32 position = NAMESPACE;
assembly {
l.slot := position
}
}
}
contracts/plugins/extensions/NamiPluginV1ExtensionBase.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '@cryptoalgebra/abstract-plugin/contracts/UpgradeableAbstractPlugin.sol';
import '@cryptoalgebra/dynamic-fee-plugin/contracts/types/AlgebraFeeConfiguration.sol';
import '../modules/extensions/VolatilityOracleExtensionModule.sol';
import '../modules/extensions/DynamicFeeExtensionModule.sol';
import '../modules/extensions/FeeOverrideExtensionModule.sol';
import '../modules/extensions/FarmingProxyExtensionModule.sol';
import '../modules/extensions/MevxExtensionModule.sol';
/// @title Nami Plugin V1 extension base
/// @notice Views and setters of every module, reached through the hot plugin's fallback delegatecall.
/// Must be deployed with the same factory and pluginFactory as the hot implementation that points at it.
abstract contract NamiPluginV1ExtensionBase is
UpgradeableAbstractPlugin,
VolatilityOracleExtensionModule,
DynamicFeeExtensionModule,
FeeOverrideExtensionModule,
FarmingProxyExtensionModule,
MevxExtensionModule
{
/// @notice Emitted when the plugin is initialized
event PluginInitialized(address indexed pool);
constructor(address _factory, address _pluginFactory) UpgradeableAbstractPlugin(_factory, _pluginFactory) {}
function initialize(
AlgebraFeeConfiguration calldata feeConfig,
address _router,
address _executor,
address _distributor,
bytes32 _configId,
uint256 _minGasLeft,
uint256 _callGasBudget
) external initializer onlyPluginFactory {
_initializeDynamicFee(feeConfig);
if (_router != address(0)) {
_initializeMevx(_router, _executor, _distributor, _configId, _minGasLeft, _callGasBudget);
}
emit PluginInitialized(_getPool());
}
/// @notice Returns the current fee, the base fee on a flat config and the volatility curve otherwise
function getCurrentFee() external view override returns (uint16 fee) {
(, int24 tick, , ) = _getPoolState();
fee = _feeForTick(tick);
}
}
contracts/plugins/modules/AntiSniperModuleUpgradeable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '@cryptoalgebra/integral-core/contracts/libraries/Plugins.sol';
import '@cryptoalgebra/integral-core/contracts/libraries/SafeTransfer.sol';
import '@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol';
import '@cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolState.sol';
import '@cryptoalgebra/abstract-plugin/contracts/UpgradeableAbstractPlugin.sol';
import 'solady/src/utils/FixedPointMathLib.sol';
import '../../libraries/AntiSniperStorage.sol';
import '../../interfaces/plugins/IAntiSniperConnector.sol';
/// @title AntiSniper module core for proxied plugins
/// @notice Hook-path logic only. Views and setters live in AntiSniperExtensionModule.
abstract contract AntiSniperModuleUpgradeable is UpgradeableAbstractPlugin {
string public constant ANTI_SNIPER_MODULE_NAME = 'Anti-Sniper Plugin';
uint8 public constant ANTI_SNIPER_PLUGIN_CONFIG = uint8(Plugins.BEFORE_SWAP_FLAG);
uint24 internal constant MAX_FEE = 900000;
uint32 internal constant MIN_PERIOD = 5 minutes;
uint32 internal constant MAX_PERIOD = 1 days;
uint16 internal constant MIN_EASE = 1000;
uint16 internal constant MAX_EASE = 5000;
uint256 internal constant MAX_START_MULTIPLE = 10e18;
uint256 internal constant FEE_DENOMINATOR = 1e6;
uint256 internal constant WAD = 1e18;
uint16 private constant EASE_ONE = 1000;
uint256 private constant EASE_TO_WAD = 1e15;
/// @dev Called in beforeSwap. Returns early when disabled.
function _antiSniperBeforeSwap(
address sender,
address _pool,
bool zeroToOne,
int256 amount,
bytes calldata data
) internal returns (bool feeCollected) {
AntiSniperStorage.Layout storage layout = AntiSniperStorage.layout();
if (layout.config.startingFee == 0) return false;
IAntiSniperConnector.AntiSniperConfig memory config = layout.config;
uint64 start = layout.startTimestamp;
if (config.disabledPriorStart) {
require(start > 0 && block.timestamp >= start, 'Trading disabled');
}
if (layout.exemptions[sender]) return false;
uint256 fee = _antiSniperFeeAmount(config, start, _pool, amount);
if (fee == 0) return false;
address token = (amount >= 0 ? zeroToOne : !zeroToOne) ? IAlgebraPool(_pool).token0() : IAlgebraPool(_pool).token1();
address recipient = config.feeReceiver != address(0) ? config.feeReceiver : address(this);
SafeTransfer.safeTransferFrom(token, _antiSniperPayer(sender, data), recipient, fee);
return true;
}
function _antiSniperFeeAmount(
IAntiSniperConnector.AntiSniperConfig memory config,
uint64 start,
address _pool,
int256 amount
) private view returns (uint256) {
uint256 amountIn = amount >= 0 ? uint256(amount) : uint256(-amount);
if (config.easeIn == 0) {
uint24 auxFee = _calculateCurrentFee(config, start);
if (auxFee == 0) return 0;
return _calculateFeeAmount(amountIn, _poolFee(_pool), auxFee);
}
uint256 weight = _curveWeight(config, start);
if (weight == 0) return 0;
return FixedPointMathLib.mulWad(amountIn, FixedPointMathLib.mulWad(_startMultiple(config.startingFee, _poolFee(_pool)), weight));
}
/// @dev Mirrors SwapRouter.SwapCallbackData
struct RouterCallbackData {
bytes path;
address payer;
}
/// @dev The router whose callback data names the payer, overridden by the plugin
function _antiSniperRouter() internal view virtual returns (address) {
return address(0);
}
/// @dev Our router names its caller as payer, so a contract account calling it pays its own fee.
/// Any other caller of the pool pays for itself. A later hop of a router multihop names the router and reverts.
function _antiSniperPayer(address sender, bytes calldata data) internal view returns (address) {
if (sender != _antiSniperRouter()) return sender;
address payer = abi.decode(data, (RouterCallbackData)).payer;
require(payer != sender, 'Anti-sniper pool must be first hop');
return payer;
}
function _currentAntiSniperMultiple() internal view returns (uint256) {
AntiSniperStorage.Layout storage layout = AntiSniperStorage.layout();
IAntiSniperConnector.AntiSniperConfig memory config = layout.config;
if (config.startingFee == 0) return 0;
(, , uint16 poolFee, ) = _getPoolState();
if (config.easeIn == 0) {
uint24 auxFee = _calculateCurrentFee(config, layout.startTimestamp);
return auxFee == 0 ? 0 : _shareToMultiple(auxFee, poolFee);
}
uint256 weight = _curveWeight(config, layout.startTimestamp);
return weight == 0 ? 0 : FixedPointMathLib.mulWad(_startMultiple(config.startingFee, poolFee), weight);
}
function _currentAntiSniperShare() internal view returns (uint24) {
AntiSniperStorage.Layout storage layout = AntiSniperStorage.layout();
IAntiSniperConnector.AntiSniperConfig memory config = layout.config;
if (config.startingFee == 0) return 0;
if (config.easeIn == 0) return _calculateCurrentFee(config, layout.startTimestamp);
uint256 multiple = _currentAntiSniperMultiple();
(, , uint16 poolFee, ) = _getPoolState();
// share = m (1 - f) / (m + 1 - f)
uint256 net = FEE_DENOMINATOR - poolFee;
return uint24(FixedPointMathLib.mulDiv(multiple, net, multiple + net * (WAD / FEE_DENOMINATOR)));
}
function _calculateCurrentFee(IAntiSniperConnector.AntiSniperConfig memory config, uint64 start) internal view returns (uint24) {
if (start == 0 || block.timestamp < start) return config.startingFee;
if (block.timestamp >= start + config.period) return 0;
uint256 elapsed = block.timestamp - start;
uint256 decay = (uint256(config.startingFee) * elapsed) / config.period;
return uint24(config.startingFee - decay);
}
/// @dev (1 - u^a)^b in WAD
function _curveWeight(IAntiSniperConnector.AntiSniperConfig memory config, uint64 start) internal view returns (uint256) {
if (start == 0 || block.timestamp <= start) return WAD;
uint256 elapsed = block.timestamp - start;
if (elapsed >= config.period) return 0;
uint256 eased = _ease((elapsed * WAD) / config.period, config.easeIn);
if (eased >= WAD) return 0;
return _ease(WAD - eased, config.easeOut);
}
function _ease(uint256 x, uint16 ease) private pure returns (uint256) {
if (ease == EASE_ONE) return x;
return uint256(FixedPointMathLib.powWad(int256(x), int256(uint256(ease) * EASE_TO_WAD)));
}
/// @dev m = (1 - f) s / (1 - f - s)
function _shareToMultiple(uint24 share, uint16 poolFee) internal pure returns (uint256) {
uint256 net = FEE_DENOMINATOR - poolFee;
return FixedPointMathLib.mulDiv(net * share, WAD, (net - share) * FEE_DENOMINATOR);
}
function _startMultiple(uint24 startingFee, uint16 poolFee) internal pure returns (uint256) {
return FixedPointMathLib.min(_shareToMultiple(startingFee, poolFee), MAX_START_MULTIPLE);
}
function _poolFee(address _pool) private view returns (uint16 poolFee) {
(, , poolFee, , , ) = IAlgebraPoolState(_pool).globalState();
}
function _calculateFeeAmount(uint256 amountIn, uint16 poolFee, uint24 auxFee) private pure returns (uint256) {
uint256 poolFeeAmount = (amountIn * poolFee) / FEE_DENOMINATOR;
uint256 netAmount = amountIn - poolFeeAmount;
uint256 targetRate = uint256(poolFee) + uint256(auxFee);
uint256 denom = FEE_DENOMINATOR - targetRate;
if (denom == 0) return 0;
return (netAmount * auxFee) / denom;
}
}
contracts/plugins/modules/DynamicFeeModuleUpgradeable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '@cryptoalgebra/integral-core/contracts/libraries/Plugins.sol';
import '@cryptoalgebra/abstract-plugin/contracts/UpgradeableAbstractPlugin.sol';
import '@cryptoalgebra/dynamic-fee-plugin/contracts/types/AlgebraFeeConfiguration.sol';
import { AlgebraFeeConfigurationU144, AlgebraFeeConfigurationU144Lib } from '@cryptoalgebra/dynamic-fee-plugin/contracts/types/AlgebraFeeConfigurationU144.sol';
import '@cryptoalgebra/dynamic-fee-plugin/contracts/libraries/AdaptiveFee.sol';
import '@cryptoalgebra/dynamic-fee-plugin/contracts/libraries/DynamicFeeStorage.sol';
/// @title DynamicFee module core for proxied plugins
/// @notice Hook-path logic only. Views and setters live in DynamicFeeExtensionModule.
abstract contract DynamicFeeModuleUpgradeable is UpgradeableAbstractPlugin {
using AlgebraFeeConfigurationU144Lib for AlgebraFeeConfiguration;
string internal constant DYNAMIC_FEE_MODULE_NAME = 'Dynamic Fee Plugin';
uint8 internal constant DYNAMIC_FEE_PLUGIN_CONFIG = uint8(Plugins.BEFORE_SWAP_FLAG | Plugins.DYNAMIC_FEE);
function _initializeDynamicFee(AlgebraFeeConfiguration memory config) internal {
AdaptiveFee.validateFeeConfiguration(config);
DynamicFeeStorage.layout().feeConfig = config.pack();
}
function _getCurrentFee(uint88 volatilityAverage) internal view returns (uint16 fee) {
AlgebraFeeConfigurationU144 feeConfig_ = DynamicFeeStorage.layout().feeConfig;
if (feeConfig_.alpha1() | feeConfig_.alpha2() == 0) return feeConfig_.baseFee();
return AdaptiveFee.getFee(volatilityAverage, feeConfig_);
}
}
contracts/plugins/modules/FarmingProxyModuleUpgradeable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '@cryptoalgebra/integral-core/contracts/libraries/Plugins.sol';
import '@cryptoalgebra/abstract-plugin/contracts/UpgradeableAbstractPlugin.sol';
import '@cryptoalgebra/farming-proxy-plugin/contracts/interfaces/IAlgebraVirtualPool.sol';
import '@cryptoalgebra/farming-proxy-plugin/contracts/libraries/FarmingProxyStorage.sol';
/// @title FarmingProxy module core for proxied plugins
/// @notice Hook-path logic only. Views and setters live in FarmingProxyExtensionModule.
abstract contract FarmingProxyModuleUpgradeable is UpgradeableAbstractPlugin {
string internal constant FARMING_PROXY_MODULE_NAME = 'Farming Proxy Plugin';
uint8 internal constant FARMING_PROXY_PLUGIN_CONFIG = uint8(Plugins.AFTER_SWAP_FLAG);
function _updateVirtualPoolTick(bool zeroToOne, int24 tick) internal {
address _incentive = FarmingProxyStorage.layout().incentive;
if (_incentive != address(0)) {
IAlgebraVirtualPool(_incentive).crossTo(tick, zeroToOne);
}
}
}
contracts/plugins/modules/FeeCurveModuleUpgradeable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import './VolatilityOracleModuleUpgradeable.sol';
import './DynamicFeeModuleUpgradeable.sol';
/// @title Fee curve shared by the hot plugins and their extensions
/// @notice Skips the 24h volatility average when the fee config is flat
abstract contract FeeCurveModuleUpgradeable is VolatilityOracleModuleUpgradeable, DynamicFeeModuleUpgradeable {
function _feeForTick(int24 tick) internal view returns (uint16) {
AlgebraFeeConfigurationU144 feeConfig_ = DynamicFeeStorage.layout().feeConfig;
// both alphas at zero is a flat fee, so the volatility average is not needed
if (feeConfig_.alpha1() | feeConfig_.alpha2() == 0) return feeConfig_.baseFee();
return AdaptiveFee.getFee(_getAverageVolatilityLast(tick), feeConfig_);
}
}
contracts/plugins/modules/FeeOverrideModuleUpgradeable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../../libraries/FeeOverrideStorage.sol';
import '../../interfaces/plugins/INamiFeeSource.sol';
import './FeeCurveModuleUpgradeable.sol';
/// @title Fee override module core for proxied plugins
/// @notice Hook-path logic only. Views and setters live in FeeOverrideExtensionModule.
abstract contract FeeOverrideModuleUpgradeable is FeeCurveModuleUpgradeable {
string internal constant FEE_OVERRIDE_MODULE_NAME = 'Fee Override Plugin';
uint16 internal constant FEE_OVERRIDE_MIN_POOL_FEE = 100;
uint32 internal constant FEE_OVERRIDE_MAX_TTL = 24 hours;
uint32 internal constant FEE_OVERRIDE_MAX_DECAY_WINDOW = 6 hours;
uint16 internal constant FEE_OVERRIDE_MAX_DISCOUNT_BPS = 5000;
uint8 internal constant FEE_SOURCE_MAX_SEGMENTS = 16;
/// @dev The fee for a swap in the given direction. Reads one storage slot on top of the fee curve, and two more
/// plus a call when a source is enabled. A failing source call reverts, so starving it of gas never buys a
/// cheaper fee
function _swapFee(int24 tick, bool zeroToOne) internal view returns (uint16) {
FeeOverrideStorage.Layout storage l = FeeOverrideStorage.layout();
uint256 base = _feeForTick(tick);
if (l.sourceEnabled) base = _segmentFee(l, base);
uint256 cap = l.cap;
if (cap == 0) return uint16(base);
uint256 side = base + (zeroToOne ? l.premium0For1 : l.premium1For0);
uint256 fee = side;
uint256 override_ = zeroToOne ? l.fee0For1 : l.fee1For0;
if (override_ != 0) {
// an override may price below the side fee only by the pool's allowed discount, 0 by default
uint256 lowest = side - (side * l.maxDiscountBps) / 10_000;
if (override_ < lowest) override_ = lowest;
if (override_ != side) {
uint256 expiresAt = l.expiresAt;
if (block.timestamp < expiresAt) {
fee = override_;
} else {
uint256 decayEnd = expiresAt + l.decayWindow;
if (block.timestamp < decayEnd) {
// fades back toward the side fee from either direction
uint256 remaining = decayEnd - block.timestamp;
fee = override_ > side
? side + ((override_ - side) * remaining) / l.decayWindow
: side - ((side - override_) * remaining) / l.decayWindow;
}
}
}
}
if (fee < l.floor) fee = l.floor;
else if (fee > cap) fee = cap;
return uint16(fee);
}
/// @dev The fee the admin assigned to the source's current segment, blended toward the next segment's fee
/// when the source is between two. An unassigned segment means the pool's own base fee
function _segmentFee(FeeOverrideStorage.Layout storage l, uint256 base) private view returns (uint256) {
(uint8 id, uint8 nextId, uint16 blendBps) = INamiFeeSource(l.source).segmentAt(block.timestamp);
uint256 fees = l.segmentFees;
uint256 fee = _feeOf(fees, id, base);
if (blendBps == 0 || nextId == id) return fee;
uint256 next = _feeOf(fees, nextId, base);
return fee > next ? fee - ((fee - next) * blendBps) / 10_000 : fee + ((next - fee) * blendBps) / 10_000;
}
function _feeOf(uint256 fees, uint8 id, uint256 base) private pure returns (uint256) {
if (id >= FEE_SOURCE_MAX_SEGMENTS) return base;
uint256 fee = (fees >> (16 * id)) & 0xffff;
return fee == 0 ? base : fee;
}
}
contracts/plugins/modules/MevxModuleUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.8.20;
import '@cryptoalgebra/integral-core/contracts/libraries/Plugins.sol';
import '@cryptoalgebra/abstract-plugin/contracts/UpgradeableAbstractPlugin.sol';
import '../../interfaces/mevx/IMevxRouter.sol';
import '../../interfaces/mevx/IMevxExecutor.sol';
import '../../interfaces/mevx/IProfitDistributor.sol';
import '../../libraries/MevxStorage.sol';
/// @title MEVX module core for proxied plugins
/// @notice Hook-path logic and the runArbitrage self-call. Views and setters live in MevxExtensionModule.
abstract contract MevxModuleUpgradeable is UpgradeableAbstractPlugin {
string internal constant MEVX_MODULE_NAME = 'MEVX Plugin';
uint8 internal constant MEVX_PLUGIN_CONFIG = uint8(Plugins.AFTER_INIT_FLAG | Plugins.AFTER_SWAP_FLAG);
uint16 internal constant ALGEBRA_POOL_TYPE = 3;
uint256 public constant MAX_MIN_GAS_LEFT = 5_000_000;
uint256 public constant MAX_CALL_GAS_BUDGET = 5_000_000;
function _getMevxExecutor() internal view returns (address) {
return MevxStorage.layout().mevxExecutor;
}
function _initializePool(address _pool, uint160 sqrtPriceX96) internal {
MevxStorage.Layout storage layout = MevxStorage.layout();
address router = layout.mevxRouter;
if (router == address(0)) return;
bytes32 poolId = bytes32(uint256(uint160(_pool)));
bytes memory data = abi.encode(sqrtPriceX96);
bytes memory initData = abi.encodeCall(IMevxRouter.initializePoolExternally, (poolId, ALGEBRA_POOL_TYPE, data));
// Non-blocking on purpose: pool initialization must not depend on the router.
address(router).call{gas: layout.callGasBudget}(initData);
}
/// @dev Route construction and execution run in a self-call capped by `callGasBudget`, so a failing or
/// gas-hungry backrun can never revert the user's swap.
function _mevxAfterSwap(address _pool, address sender, bool zeroToOne, int256 amount0, int256 amount1) internal {
MevxStorage.Layout storage layout = MevxStorage.layout();
if (layout.mevxRouter == address(0)) return;
if (sender != layout.mevxExecutor) {
require(gasleft() >= layout.minGasLeft, 'Insufficient gas for afterSwap hook');
}
bytes memory branchData = abi.encodeCall(this.runArbitrage, (bytes32(uint256(uint160(_pool))), zeroToOne, amount0, amount1, sender));
address(this).call{gas: layout.callGasBudget}(branchData);
}
/// @notice Self-call entry point used to cap the gas spent by route construction and execution
function runArbitrage(bytes32 poolId, bool zeroToOne, int256 amount0, int256 amount1, address sender) external {
require(msg.sender == address(this), 'self only');
MevxStorage.Layout storage layout = MevxStorage.layout();
(bool successInitialArbCheck, bytes memory returnDataInitialArbCheck) = address(layout.mevxRouter).call(
abi.encodeWithSelector(IMevxRouter.initialArbCheck.selector, poolId, !zeroToOne)
);
// The executor's own backrun must not trigger another backrun
if (sender == layout.mevxExecutor) {
return;
}
if (!successInitialArbCheck || returnDataInitialArbCheck.length != 64) {
return;
}
(bool isArbPossible, bytes16 arbData) = abi.decode(returnDataInitialArbCheck, (bool, bytes16));
if (!isArbPossible) {
return;
}
(bool success, bytes memory returnData) = address(layout.mevxRouter).call(
abi.encodeWithSelector(IMevxRouter.constructArbitrageRoute.selector, poolId, zeroToOne, arbData, amount0, amount1)
);
if (!success || returnData.length < 224) {
return;
}
address profitToken;
address[] memory pools;
uint256 amountIn;
bytes memory encodedRoute;
{
bool routeFound;
(routeFound, profitToken, pools, amountIn, encodedRoute) = abi.decode(returnData, (bool, address, address[], uint256, bytes));
if (!routeFound || pools.length == 0 || amountIn == 0 || encodedRoute.length == 0) {
return;
}
}
address _mevxProfitDistributor = layout.mevxProfitDistributor;
try IMevxExecutor(layout.mevxExecutor).executeRoute(encodedRoute, pools, amountIn, profitToken, _mevxProfitDistributor) {
try IProfitDistributor(_mevxProfitDistributor).distributeProfit(layout.mevxConfigId, profitToken) {} catch {}
} catch {}
}
}
contracts/plugins/modules/VolatilityOracleModuleUpgradeable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '@cryptoalgebra/integral-core/contracts/libraries/Plugins.sol';
import '@cryptoalgebra/abstract-plugin/contracts/UpgradeableAbstractPlugin.sol';
import '@cryptoalgebra/volatility-oracle-plugin/contracts/libraries/VolatilityOracle.sol';
import '@cryptoalgebra/volatility-oracle-plugin/contracts/libraries/VolatilityOracleStorage.sol';
/// @title VolatilityOracle module core for proxied plugins
/// @notice Hook-path logic only. Views and setters live in VolatilityOracleExtensionModule.
abstract contract VolatilityOracleModuleUpgradeable is UpgradeableAbstractPlugin {
uint256 internal constant UINT16_MODULO = 65536;
using VolatilityOracle for VolatilityOracle.Timepoint[UINT16_MODULO];
string internal constant VOLATILITY_ORACLE_MODULE_NAME = 'Volatility Oracle Plugin';
uint8 internal constant VOLATILITY_ORACLE_PLUGIN_CONFIG = uint8(Plugins.AFTER_INIT_FLAG | Plugins.BEFORE_SWAP_FLAG);
function _initialize_TWAP(int24 tick) internal {
VolatilityOracleStorage.Layout storage layout = VolatilityOracleStorage.layout();
uint32 time = _blockTimestamp();
layout.timepoints.initialize(time, tick);
layout.lastTimepointTimestamp = time;
layout.isInitialized = true;
}
function _writeTimepoint(int24 tick) internal {
VolatilityOracleStorage.Layout storage layout = VolatilityOracleStorage.layout();
require(layout.isInitialized, 'Not initialized');
uint32 currentTimestamp = _blockTimestamp();
if (layout.lastTimepointTimestamp == currentTimestamp) return;
(uint16 newLastIndex, ) = layout.timepoints.write(layout.timepointIndex, currentTimestamp, tick);
layout.timepointIndex = newLastIndex;
layout.lastTimepointTimestamp = currentTimestamp;
}
function _getAverageVolatilityLast(int24 tick) internal view returns (uint88 volatilityAverage) {
VolatilityOracleStorage.Layout storage layout = VolatilityOracleStorage.layout();
uint16 lastIndex = layout.timepointIndex;
uint16 oldestIndex = layout.timepoints.getOldestIndex(lastIndex);
return layout.timepoints.getAverageVolatility(_blockTimestamp(), tick, lastIndex, oldestIndex);
}
}
contracts/plugins/modules/extensions/AntiSniperExtensionModule.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../AntiSniperModuleUpgradeable.sol';
/// @title AntiSniper views and setters, reached through the hot plugin's fallback
abstract contract AntiSniperExtensionModule is AntiSniperModuleUpgradeable, IAntiSniperConnector {
/// @inheritdoc IAntiSniperConnector
function antiSniperConfig() external view override returns (AntiSniperConfig memory) {
return AntiSniperStorage.layout().config;
}
/// @inheritdoc IAntiSniperConnector
function startTimestamp() external view override returns (uint64) {
return AntiSniperStorage.layout().startTimestamp;
}
/// @inheritdoc IAntiSniperConnector
function isExemptFromAntiSniper(address account) external view override returns (bool) {
return AntiSniperStorage.layout().exemptions[account];
}
/// @inheritdoc IAntiSniperConnector
function setAntiSniperConfig(AntiSniperConfig calldata config) external override {
_authorize();
AntiSniperStorage.Layout storage layout = AntiSniperStorage.layout();
uint64 currentStartTimestamp = layout.startTimestamp;
if (config.startingFee > 0) {
require(config.feeReceiver != address(0), 'Zero receiver');
require(config.startingFee <= MAX_FEE, 'Fee too high');
require(config.period >= MIN_PERIOD && config.period <= MAX_PERIOD, 'Invalid period');
}
if (config.easeIn != 0 || config.easeOut != 0) {
require(config.easeIn >= MIN_EASE && config.easeIn <= MAX_EASE, 'Invalid easeIn');
require(config.easeOut >= MIN_EASE && config.easeOut <= MAX_EASE, 'Invalid easeOut');
}
// Full config only before trading starts, feeReceiver only afterwards
if (currentStartTimestamp == 0 || block.timestamp < currentStartTimestamp) {
layout.config = config;
} else {
layout.config.feeReceiver = config.feeReceiver;
}
emit AntiSniperConfigured(layout.config);
}
/// @inheritdoc IAntiSniperConnector
function setStartTimestamp(uint64 timestamp) external override {
_authorize();
AntiSniperStorage.Layout storage layout = AntiSniperStorage.layout();
uint64 currentStartTimestamp = layout.startTimestamp;
require(timestamp > block.timestamp, 'Must be future');
require(currentStartTimestamp == 0 || block.timestamp < currentStartTimestamp, 'Already started');
layout.startTimestamp = timestamp;
emit StartTimestampSet(timestamp);
}
/// @inheritdoc IAntiSniperConnector
function setExemption(address account, bool exempt) external override {
_authorize();
AntiSniperStorage.layout().exemptions[account] = exempt;
emit ExemptionUpdated(account, exempt);
}
}
contracts/plugins/modules/extensions/DynamicFeeExtensionModule.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '@cryptoalgebra/dynamic-fee-plugin/contracts/interfaces/IDynamicFeeManager.sol';
import '../DynamicFeeModuleUpgradeable.sol';
/// @title DynamicFee views and setters, reached through the hot plugin's fallback
abstract contract DynamicFeeExtensionModule is DynamicFeeModuleUpgradeable, IDynamicFeeManager {
using AlgebraFeeConfigurationU144Lib for AlgebraFeeConfiguration;
/// @inheritdoc IDynamicFeeManager
function feeConfig()
external
view
override
returns (uint16 alpha1, uint16 alpha2, uint32 beta1, uint32 beta2, uint16 gamma1, uint16 gamma2, uint16 baseFee)
{
AlgebraFeeConfigurationU144 feeConfig_ = DynamicFeeStorage.layout().feeConfig;
(alpha1, alpha2) = (feeConfig_.alpha1(), feeConfig_.alpha2());
(beta1, beta2) = (feeConfig_.beta1(), feeConfig_.beta2());
(gamma1, gamma2) = (feeConfig_.gamma1(), feeConfig_.gamma2());
baseFee = feeConfig_.baseFee();
}
/// @inheritdoc IDynamicFeeManager
function changeFeeConfiguration(AlgebraFeeConfiguration calldata config) external override {
_authorize();
AdaptiveFee.validateFeeConfiguration(config);
DynamicFeeStorage.layout().feeConfig = config.pack();
emit FeeConfiguration(config);
}
}
contracts/plugins/modules/extensions/FarmingProxyExtensionModule.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol';
import '@cryptoalgebra/farming-proxy-plugin/contracts/interfaces/IFarmingPlugin.sol';
import '@cryptoalgebra/farming-proxy-plugin/contracts/interfaces/IFarmingPluginFactory.sol';
import '../FarmingProxyModuleUpgradeable.sol';
/// @title FarmingProxy views and setters, reached through the hot plugin's fallback
abstract contract FarmingProxyExtensionModule is FarmingProxyModuleUpgradeable, IFarmingPlugin {
using Plugins for uint8;
/// @inheritdoc IFarmingPlugin
function incentive() external view override returns (address) {
return FarmingProxyStorage.layout().incentive;
}
/// @inheritdoc IFarmingPlugin
function setIncentive(address newIncentive) external override {
FarmingProxyStorage.Layout storage layout = FarmingProxyStorage.layout();
bool toConnect = newIncentive != address(0);
bool accessAllowed;
if (toConnect) {
accessAllowed = msg.sender == IFarmingPluginFactory(pluginFactory).farmingAddress();
} else {
if (layout.lastIncentiveOwner != address(0)) accessAllowed = msg.sender == layout.lastIncentiveOwner;
if (!accessAllowed) accessAllowed = msg.sender == IFarmingPluginFactory(pluginFactory).farmingAddress();
}
require(accessAllowed, 'Not allowed to set incentive');
bool isPluginConnected = _getPluginInPool() == address(this);
if (toConnect) require(isPluginConnected, 'Plugin not attached');
address currentIncentive = layout.incentive;
require(currentIncentive != newIncentive, 'Already active');
if (toConnect) require(currentIncentive == address(0), 'Has active incentive');
layout.incentive = newIncentive;
if (toConnect) {
layout.lastIncentiveOwner = msg.sender;
} else {
layout.lastIncentiveOwner = address(0);
}
if (isPluginConnected) {
(, , , uint8 currentPluginConfig) = _getPoolState();
uint8 newPluginConfig = currentPluginConfig | uint8(Plugins.AFTER_SWAP_FLAG);
if (currentPluginConfig != newPluginConfig) {
IAlgebraPool(_getPool()).setPluginConfig(newPluginConfig);
}
}
emit Incentive(newIncentive);
}
/// @inheritdoc IFarmingPlugin
function isIncentiveConnected(address targetIncentive) external view override returns (bool) {
if (FarmingProxyStorage.layout().incentive != targetIncentive) return false;
if (_getPluginInPool() != address(this)) return false;
(, , , uint8 pluginConfig) = _getPoolState();
if (!pluginConfig.hasFlag(Plugins.AFTER_SWAP_FLAG)) return false;
return true;
}
/// @inheritdoc IFarmingPlugin
function getPool() external view override returns (address) {
return _getPool();
}
}
contracts/plugins/modules/extensions/FeeOverrideExtensionModule.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../../../interfaces/plugins/INamiFeeOverride.sol';
import '../../../interfaces/plugins/INamiFeeSourceConsumer.sol';
import '../FeeOverrideModuleUpgradeable.sol';
/// @title Fee override and fee source views and setters, reached through the hot plugin's fallback
abstract contract FeeOverrideExtensionModule is FeeOverrideModuleUpgradeable, INamiFeeOverride, INamiFeeSourceConsumer {
/// @inheritdoc INamiFeeOverride
uint16 public constant override MIN_POOL_FEE = FEE_OVERRIDE_MIN_POOL_FEE;
/// @inheritdoc INamiFeeOverride
uint32 public constant override MAX_TTL = FEE_OVERRIDE_MAX_TTL;
/// @inheritdoc INamiFeeOverride
uint32 public constant override MAX_DECAY_WINDOW = FEE_OVERRIDE_MAX_DECAY_WINDOW;
/// @inheritdoc INamiFeeOverride
uint16 public constant override MAX_DISCOUNT_BPS = FEE_OVERRIDE_MAX_DISCOUNT_BPS;
// ========== OVERRIDES ==========
/// @inheritdoc INamiFeeOverride
function feeBounds() external view override returns (FeeBounds memory bounds) {
FeeOverrideStorage.Layout storage l = FeeOverrideStorage.layout();
bounds = FeeBounds({
floor: l.floor,
cap: l.cap,
premium0For1: l.premium0For1,
premium1For0: l.premium1For0,
decayWindow: l.decayWindow,
maxDiscountBps: l.maxDiscountBps
});
}
/// @inheritdoc INamiFeeOverride
function feeOverride() external view override returns (FeeOverride memory override_) {
FeeOverrideStorage.Layout storage l = FeeOverrideStorage.layout();
override_ = FeeOverride({fee0For1: l.fee0For1, fee1For0: l.fee1For0, expiresAt: l.expiresAt});
}
/// @inheritdoc INamiFeeOverride
function swapFee(bool zeroToOne) external view override returns (uint16) {
(, int24 tick, , ) = _getPoolState();
return _swapFee(tick, zeroToOne);
}
/// @inheritdoc INamiFeeOverride
function setFeeBounds(FeeBounds calldata bounds) external override {
_authorize();
if (
bounds.floor < FEE_OVERRIDE_MIN_POOL_FEE ||
bounds.floor > bounds.cap ||
bounds.premium0For1 > bounds.cap - bounds.floor ||
bounds.premium1For0 > bounds.cap - bounds.floor ||
bounds.decayWindow > FEE_OVERRIDE_MAX_DECAY_WINDOW ||
bounds.maxDiscountBps > FEE_OVERRIDE_MAX_DISCOUNT_BPS
) revert InvalidBounds();
FeeOverrideStorage.Layout storage l = FeeOverrideStorage.layout();
l.floor = bounds.floor;
l.cap = bounds.cap;
l.premium0For1 = bounds.premium0For1;
l.premium1For0 = bounds.premium1For0;
l.decayWindow = bounds.decayWindow;
l.maxDiscountBps = bounds.maxDiscountBps;
emit FeeBoundsSet(bounds);
}
/// @inheritdoc INamiFeeOverride
function setFeeOverride(uint16 fee0For1, uint16 fee1For0, uint32 ttl) external override {
_authorize();
FeeOverrideStorage.Layout storage l = FeeOverrideStorage.layout();
uint16 cap = l.cap;
if (cap == 0) revert BoundsNotSet();
if (fee0For1 == 0 && fee1For0 == 0) revert EmptyOverride();
if (ttl == 0 || ttl > FEE_OVERRIDE_MAX_TTL) revert InvalidTtl();
uint16 floor = l.floor;
_checkSide(fee0For1, floor, cap);
_checkSide(fee1For0, floor, cap);
uint40 expiresAt = uint40(block.timestamp + ttl);
l.fee0For1 = fee0For1;
l.fee1For0 = fee1For0;
l.expiresAt = expiresAt;
emit FeeOverrideSet(fee0For1, fee1For0, expiresAt);
}
/// @inheritdoc INamiFeeOverride
function clearFeeOverride() external override {
_authorize();
FeeOverrideStorage.Layout storage l = FeeOverrideStorage.layout();
l.fee0For1 = 0;
l.fee1For0 = 0;
l.expiresAt = 0;
emit FeeOverrideCleared();
}
// ========== FEE SOURCE ==========
/// @inheritdoc INamiFeeSourceConsumer
uint8 public constant override MAX_SEGMENTS = FEE_SOURCE_MAX_SEGMENTS;
/// @inheritdoc INamiFeeSourceConsumer
function feeSource() external view override returns (address source, bool enabled) {
FeeOverrideStorage.Layout storage l = FeeOverrideStorage.layout();
return (l.source, l.sourceEnabled);
}
/// @inheritdoc INamiFeeSourceConsumer
function segmentFees() external view override returns (uint16[16] memory fees) {
uint256 packed = FeeOverrideStorage.layout().segmentFees;
for (uint256 i; i < FEE_SOURCE_MAX_SEGMENTS; ++i) fees[i] = uint16(packed >> (16 * i));
}
/// @inheritdoc INamiFeeSourceConsumer
function setFeeSource(address source) external override {
_authorize();
if (source.code.length == 0) revert InvalidFeeSource();
FeeOverrideStorage.Layout storage l = FeeOverrideStorage.layout();
l.source = source;
// ids mean different things on another source, so its fees start empty and it must be enabled again
l.segmentFees = 0;
if (l.sourceEnabled) {
l.sourceEnabled = false;
emit FeeSourceEnabled(false);
}
emit FeeSourceSet(source);
}
/// @inheritdoc INamiFeeSourceConsumer
function setSegmentFees(uint16[16] calldata fees) external override {
_authorize();
FeeOverrideStorage.Layout storage l = FeeOverrideStorage.layout();
address source = l.source;
if (source == address(0)) revert InvalidFeeSource();
uint256 count = INamiFeeSource(source).segmentCount();
uint256 packed;
for (uint256 i; i < FEE_SOURCE_MAX_SEGMENTS; ++i) {
// a fee on an id the source never returns is a mistake worth catching, and a fee under the pool minimum
// would go unclamped on a pool with no bounds
if (fees[i] != 0 && (i >= count || fees[i] < FEE_OVERRIDE_MIN_POOL_FEE)) revert InvalidSegmentFees();
packed |= uint256(fees[i]) << (16 * i);
}
l.segmentFees = packed;
emit SegmentFeesSet(fees);
}
/// @inheritdoc INamiFeeSourceConsumer
function setFeeSourceEnabled(bool enabled) external override {
_authorize();
FeeOverrideStorage.Layout storage l = FeeOverrideStorage.layout();
if (enabled) {
address source = l.source;
if (source == address(0)) revert InvalidFeeSource();
// a source that cannot answer would block this pool's swaps, so it is refused here instead
try INamiFeeSource(source).segmentAt(block.timestamp) {} catch {
revert InvalidFeeSource();
}
}
l.sourceEnabled = enabled;
emit FeeSourceEnabled(enabled);
}
function _checkSide(uint16 fee, uint16 floor, uint16 cap) private pure {
if (fee == 0) return;
if (fee > cap) revert FeeAboveCap();
if (fee < floor) revert FeeBelowFloor();
}
}
contracts/plugins/modules/extensions/MevxExtensionModule.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.8.20;
import '../../../interfaces/mevx/IMevxPlugin.sol';
import '../MevxModuleUpgradeable.sol';
/// @title MEVX views and setters, reached through the hot plugin's fallback
abstract contract MevxExtensionModule is MevxModuleUpgradeable, IMevxPlugin {
/// @dev A zero callGasBudget falls back to the maximum, so a factory without a default keeps the old seed
function _initializeMevx(
address mevxRouter,
address mevxExecutor,
address profitDistributor,
bytes32 configId,
uint256 minGasLeft,
uint256 callGasBudget
) internal {
if (callGasBudget == 0) callGasBudget = MAX_CALL_GAS_BUDGET;
MevxStorage.Layout storage layout = MevxStorage.layout();
layout.mevxRouter = mevxRouter;
layout.mevxExecutor = mevxExecutor;
layout.mevxProfitDistributor = profitDistributor;
layout.mevxConfigId = configId;
layout.minGasLeft = minGasLeft;
layout.callGasBudget = callGasBudget;
emit MevxRouterSet(address(0), mevxRouter);
emit MevxExecutorSet(address(0), mevxExecutor);
emit ProfitDistributorSet(address(0), profitDistributor);
emit ConfigIdSet(bytes32(0), configId);
emit MinGasLeftSet(0, minGasLeft);
emit CallGasBudgetSet(0, callGasBudget);
}
function getMevxRouter() external view override returns (address) {
return MevxStorage.layout().mevxRouter;
}
function getMevxExecutor() external view override returns (address) {
return _getMevxExecutor();
}
function getProfitDistributor() external view override returns (address) {
return MevxStorage.layout().mevxProfitDistributor;
}
function getConfigId() external view override returns (bytes32) {
return MevxStorage.layout().mevxConfigId;
}
function getMinGasLeft() external view override returns (uint256) {
return MevxStorage.layout().minGasLeft;
}
function getCallGasBudget() external view override returns (uint256) {
return MevxStorage.layout().callGasBudget;
}
function setConfigId(bytes32 _configId) external override {
_authorize();
MevxStorage.Layout storage layout = MevxStorage.layout();
bytes32 oldConfigId = layout.mevxConfigId;
layout.mevxConfigId = _configId;
emit ConfigIdSet(oldConfigId, _configId);
}
function setProfitDistributor(address _profitDistributor) external override {
_authorize();
require(_profitDistributor != address(0), 'Invalid distributor');
MevxStorage.Layout storage layout = MevxStorage.layout();
address oldProfitDistributor = layout.mevxProfitDistributor;
layout.mevxProfitDistributor = _profitDistributor;
emit ProfitDistributorSet(oldProfitDistributor, _profitDistributor);
}
function setMevxExecutor(address _mevxExecutor) external override {
_authorize();
require(_mevxExecutor != address(0), 'Invalid executor');
MevxStorage.Layout storage layout = MevxStorage.layout();
address oldMevxExecutor = layout.mevxExecutor;
layout.mevxExecutor = _mevxExecutor;
emit MevxExecutorSet(oldMevxExecutor, _mevxExecutor);
}
function setMevxRouter(address _mevxRouter) external override {
_authorize();
require(_mevxRouter != address(0), 'Invalid router');
MevxStorage.Layout storage layout = MevxStorage.layout();
address oldMevxRouter = layout.mevxRouter;
layout.mevxRouter = _mevxRouter;
emit MevxRouterSet(oldMevxRouter, _mevxRouter);
}
function setMinGasLeft(uint256 _minGasLeft) external override {
_authorize();
require(_minGasLeft <= MAX_MIN_GAS_LEFT, 'minGasLeft too high');
MevxStorage.Layout storage layout = MevxStorage.layout();
uint256 oldMinGasLeft = layout.minGasLeft;
layout.minGasLeft = _minGasLeft;
emit MinGasLeftSet(oldMinGasLeft, _minGasLeft);
}
function setCallGasBudget(uint256 _callGasBudget) external override {
_authorize();
require(_callGasBudget <= MAX_CALL_GAS_BUDGET, 'callGasBudget too high');
MevxStorage.Layout storage layout = MevxStorage.layout();
uint256 oldCallGasBudget = layout.callGasBudget;
layout.callGasBudget = _callGasBudget;
emit CallGasBudgetSet(oldCallGasBudget, _callGasBudget);
}
}
contracts/plugins/modules/extensions/VolatilityOracleExtensionModule.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '@cryptoalgebra/volatility-oracle-plugin/contracts/interfaces/IVolatilityOracle.sol';
import '../VolatilityOracleModuleUpgradeable.sol';
/// @title VolatilityOracle views and setters, reached through the hot plugin's fallback
abstract contract VolatilityOracleExtensionModule is VolatilityOracleModuleUpgradeable, IVolatilityOracle {
using VolatilityOracle for VolatilityOracle.Timepoint[UINT16_MODULO];
/// @inheritdoc IVolatilityOracle
function timepoints(
uint256 index
)
external
view
override
returns (
bool initialized,
uint32 blockTimestamp,
int56 tickCumulative,
uint88 volatilityCumulative,
int24 tick,
int24 averageTick,
uint16 windowStartIndex
)
{
VolatilityOracle.Timepoint storage tp = VolatilityOracleStorage.layout().timepoints[index];
return (tp.initialized, tp.blockTimestamp, tp.tickCumulative, tp.volatilityCumulative, tp.tick, tp.averageTick, tp.windowStartIndex);
}
/// @inheritdoc IVolatilityOracle
function timepointIndex() external view override returns (uint16) {
return VolatilityOracleStorage.layout().timepointIndex;
}
/// @inheritdoc IVolatilityOracle
function initialize() external override {
require(!VolatilityOracleStorage.layout().isInitialized, 'Already initialized');
(uint160 price, int24 tick, , ) = _getPoolState();
require(price != 0, 'Pool is not initialized');
_initialize_TWAP(tick);
}
/// @inheritdoc IVolatilityOracle
function lastTimepointTimestamp() public view override returns (uint32) {
return VolatilityOracleStorage.layout().lastTimepointTimestamp;
}
/// @inheritdoc IVolatilityOracle
function isInitialized() external view override returns (bool) {
return VolatilityOracleStorage.layout().isInitialized;
}
/// @inheritdoc IVolatilityOracle
function getSingleTimepoint(uint32 secondsAgo) external view override returns (int56 tickCumulative, uint88 volatilityCumulative) {
VolatilityOracleStorage.Layout storage layout = VolatilityOracleStorage.layout();
(, int24 tick, , ) = _getPoolState();
uint16 lastIndex = layout.timepointIndex;
uint16 oldestIndex = layout.timepoints.getOldestIndex(lastIndex);
VolatilityOracle.Timepoint memory result = layout.timepoints.getSingleTimepoint(
_blockTimestamp(),
secondsAgo,
tick,
lastIndex,
oldestIndex
);
return (result.tickCumulative, result.volatilityCumulative);
}
/// @inheritdoc IVolatilityOracle
function getTimepoints(
uint32[] memory secondsAgos
) external view override returns (int56[] memory tickCumulatives, uint88[] memory volatilityCumulatives) {
VolatilityOracleStorage.Layout storage layout = VolatilityOracleStorage.layout();
(, int24 tick, , ) = _getPoolState();
uint16 lastIndex = layout.timepointIndex;
return layout.timepoints.getTimepoints(_blockTimestamp(), secondsAgos, tick, lastIndex);
}
/// @inheritdoc IVolatilityOracle
function prepayTimepointsStorageSlots(uint16 startIndex, uint16 amount) external override {
_authorize();
VolatilityOracleStorage.Layout storage layout = VolatilityOracleStorage.layout();
require(!layout.timepoints[startIndex].initialized, 'Already initialized');
require(amount > 0 && type(uint16).max - startIndex >= amount, 'Invalid amount');
unchecked {
for (uint256 i = startIndex; i < startIndex + amount; ++i) {
layout.timepoints[i].blockTimestamp = 1;
}
}
}
}
solady/src/utils/FixedPointMathLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error ExpOverflow();
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error FactorialOverflow();
/// @dev The operation failed, due to an overflow.
error RPowOverflow();
/// @dev The mantissa is too big to fit.
error MantissaOverflow();
/// @dev The operation failed, due to an multiplication overflow.
error MulWadFailed();
/// @dev The operation failed, due to an multiplication overflow.
error SMulWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error DivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error SDivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error MulDivFailed();
/// @dev The division failed, as the denominator is zero.
error DivFailed();
/// @dev The full precision multiply-divide operation failed, either due
/// to the result being larger than 256 bits, or a division by a zero.
error FullMulDivFailed();
/// @dev The output is undefined, as the input is less-than-or-equal to zero.
error LnWadUndefined();
/// @dev The input outside the acceptable domain.
error OutOfDomain();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The scalar of ETH and most ERC20s.
uint256 internal constant WAD = 1e18;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIMPLIFIED FIXED POINT OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if gt(x, div(not(0), y)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up.
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if iszero(eq(div(z, y), x)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, WAD)
// Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
if iszero(mul(y, eq(sdiv(z, WAD), x))) {
mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up.
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
/// Note: This function is an approximation.
function powWad(int256 x, int256 y) internal pure returns (int256) {
// Using `ln(x)` means `x` must be greater than 0.
return expWad((lnWad(x) * y) / int256(WAD));
}
/// @dev Returns `exp(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function expWad(int256 x) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero.
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion
// is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
x = (x << 78) / 5 ** 18;
// Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
// of two such that exp(x) = exp(x') * 2**k, where k is an integer.
// Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
x = x - k * 54916777467707473351141471128;
// `k` is in the range `[-61, 195]`.
// Evaluate using a (6, 7)-term rational approximation.
// `p` is made monic, we'll multiply by a scale factor later.
int256 y = x + 1346386616545796478920950773328;
y = ((y * x) >> 96) + 57155421227552351082224309758442;
int256 p = y + x - 94201549194550492254356042504812;
p = ((p * y) >> 96) + 28719021644029726153956944680412240;
p = p * x + (4385272521454847904659076985693276 << 96);
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
int256 q = x - 2855989394907223263936484059900;
q = ((q * x) >> 96) + 50020603652535783019961831881945;
q = ((q * x) >> 96) - 533845033583426703283633433725380;
q = ((q * x) >> 96) + 3604857256930695427073651918091429;
q = ((q * x) >> 96) - 14423608567350463180887372962807573;
q = ((q * x) >> 96) + 26449188498355588339934803723976023;
/// @solidity memory-safe-assembly
assembly {
// Div in assembly because solidity adds a zero check despite the unchecked.
// The q polynomial won't have zeros in the domain as all its roots are complex.
// No scaling is necessary because p is already `2**96` too large.
r := sdiv(p, q)
}
// r should be in the range `(0.09, 0.25) * 2**96`.
// We now need to multiply r by:
// - The scale factor `s ≈ 6.031367120`.
// - The `2**k` factor from the range reduction.
// - The `1e18 / 2**96` factor for base conversion.
// We do this all at once, with an intermediate result in `2**213`
// basis, so the final right shift is always by a positive amount.
r = int256(
(uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
);
}
}
/// @dev Returns `ln(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function lnWad(int256 x) internal pure returns (int256 r) {
/// @solidity memory-safe-assembly
assembly {
// We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
// We do this by multiplying by `2**96 / 10**18`. But since
// `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
// and add `ln(2**96 / 10**18)` at the end.
// Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// We place the check here for more optimal stack operations.
if iszero(sgt(x, 0)) {
mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
revert(0x1c, 0x04)
}
// forgefmt: disable-next-item
r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
// Reduce range of x to (1, 2) * 2**96
// ln(2^k * x) = k * ln(2) + ln(x)
x := shr(159, shl(r, x))
// Evaluate using a (8, 8)-term rational approximation.
// `p` is made monic, we will multiply by a scale factor later.
// forgefmt: disable-next-item
let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
sar(96, mul(add(43456485725739037958740375743393,
sar(96, mul(add(24828157081833163892658089445524,
sar(96, mul(add(3273285459638523848632254066296,
x), x))), x))), x)), 11111509109440967052023855526967)
p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
// `q` is monic by convention.
let q := add(5573035233440673466300451813936, x)
q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
q := add(909429971244387300277376558375, sar(96, mul(x, q)))
// `p / q` is in the range `(0, 0.125) * 2**96`.
// Finalization, we need to:
// - Multiply by the scale factor `s = 5.549…`.
// - Add `ln(2**96 / 10**18)`.
// - Add `k * ln(2)`.
// - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
// The q polynomial is known not to have zeros in the domain.
// No scaling required because p is already `2**96` too large.
p := sdiv(p, q)
// Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
p := mul(1677202110996718588342820967067443963516166, p)
// Add `ln(2) * k * 5**18 * 2**192`.
// forgefmt: disable-next-item
p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
// Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
// Base conversion: mul `2**18 / 2**192`.
r := sar(174, p)
}
}
/// @dev Returns `W_0(x)`, denominated in `WAD`.
/// See: https://en.wikipedia.org/wiki/Lambert_W_function
/// a.k.a. Product log function. This is an approximation of the principal branch.
/// Note: This function is an approximation. Monotonically increasing.
function lambertW0Wad(int256 x) internal pure returns (int256 w) {
// forgefmt: disable-next-item
unchecked {
if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
(int256 wad, int256 p) = (int256(WAD), x);
uint256 c; // Whether we need to avoid catastrophic cancellation.
uint256 i = 4; // Number of iterations.
if (w <= 0x1ffffffffffff) {
if (-0x4000000000000 <= w) {
i = 1; // Inputs near zero only take one step to converge.
} else if (w <= -0x3ffffffffffffff) {
i = 32; // Inputs near `-1/e` take very long to converge.
}
} else if (uint256(w >> 63) == uint256(0)) {
/// @solidity memory-safe-assembly
assembly {
// Inline log2 for more performance, since the range is small.
let v := shr(49, w)
let l := shl(3, lt(0xff, v))
l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
c := gt(l, 60)
i := add(2, add(gt(l, 53), c))
}
} else {
int256 ll = lnWad(w = lnWad(w));
/// @solidity memory-safe-assembly
assembly {
// `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
i := add(3, iszero(shr(68, x)))
c := iszero(shr(143, x))
}
if (c == uint256(0)) {
do { // If `x` is big, use Newton's so that intermediate values won't overflow.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := mul(w, div(e, wad))
w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
}
if (p <= w) break;
p = w;
} while (--i != uint256(0));
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
return w;
}
}
do { // Otherwise, use Halley's for faster convergence.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := add(w, wad)
let s := sub(mul(w, e), mul(x, wad))
w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
}
if (p <= w) break;
p = w;
} while (--i != c);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
// For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
// R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
if (c == uint256(0)) return w;
int256 t = w | 1;
/// @solidity memory-safe-assembly
assembly {
x := sdiv(mul(x, wad), t)
}
x = (t * (wad + lnWad(x)));
/// @solidity memory-safe-assembly
assembly {
w := sdiv(x, add(wad, t))
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GENERAL NUMBER UTILITIES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `a * b == x * y`, with full precision.
function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// 512-bit multiply `[p1 p0] = x * y`.
// 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 = p1 * 2**256 + p0`.
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`.
for {} 1 {} {
// If overflows.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
/*------------------- 512 by 256 division --------------------*/
// Make division exact by subtracting the remainder from `[p1 p0]`.
let r := mulmod(x, y, d) // Compute remainder using mulmod.
let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
// Make sure `z` is less than `2**256`. Also prevents `d == 0`.
// Placing the check here seems to give more optimal stack operations.
if iszero(gt(d, p1)) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
d := div(d, t) // Divide `d` by `t`, which is a power of two.
// Invert `d mod 2**256`
// Now that `d` is an odd number, it has an inverse
// modulo `2**256` such that `d * inv = 1 mod 2**256`.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, `d * inv = 1 mod 2**4`.
let inv := xor(2, mul(3, d))
// 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 := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
z :=
mul(
// Divide [p1 p0] by the factors of two.
// Shift in bits from `p1` into `p0`. For this we need
// to flip `t` such that it is `2**256 / t`.
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
)
break
}
z := div(z, d)
break
}
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
/// Performs the full 512 bit calculation regardless.
function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z)))
let t := and(d, sub(0, d))
let r := mulmod(x, y, d)
d := div(d, t)
let inv := xor(2, mul(3, d))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
z :=
mul(
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv)
)
}
}
/// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Uniswap-v3-core under MIT license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
z = fullMulDiv(x, y, d);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
z := add(z, 1)
if iszero(z) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
/// Throws if result overflows a uint256.
/// Credit to Philogy under MIT license:
/// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
for {} 1 {} {
if iszero(or(iszero(x), eq(div(z, x), y))) {
let k := and(n, 0xff) // `n`, cleaned.
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
// | p1 | z |
// Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 |
// Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 |
// Check that final `z` doesn't overflow by checking that p1_0 = 0.
if iszero(shr(k, p1)) {
z := add(shl(sub(256, k), p1), shr(k, z))
break
}
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
z := shr(and(n, 0xff), z)
break
}
}
}
/// @dev Returns `floor(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := div(z, d)
}
}
/// @dev Returns `ceil(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(z, d))), div(z, d))
}
}
/// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
/// @solidity memory-safe-assembly
assembly {
let g := n
let r := mod(a, n)
for { let y := 1 } 1 {} {
let q := div(g, r)
let t := g
g := r
r := sub(t, mul(r, q))
let u := x
x := y
y := sub(u, mul(y, q))
if iszero(r) { break }
}
x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
}
}
/// @dev Returns `ceil(x / d)`.
/// Reverts if `d` is zero.
function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
if iszero(d) {
mstore(0x00, 0x65244e4e) // `DivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(x, d))), div(x, d))
}
}
/// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `max(0, x - y)`.
function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x + y)`.
function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(0, lt(add(x, y), x)), add(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x * y)`.
function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `x != 0 ? x : y`, without branching.
function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != bytes32(0) ? x : y`, without branching.
function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != address(0) ? x : y`, without branching.
function coalesce(address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(shl(96, x))))
}
}
/// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
/// Reverts if the computation overflows.
function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
if x {
z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
let half := shr(1, b) // Divide `b` by 2.
// Divide `y` by 2 every iteration.
for { y := shr(1, y) } y { y := shr(1, y) } {
let xx := mul(x, x) // Store x squared.
let xxRound := add(xx, half) // Round to the nearest number.
// Revert if `xx + half` overflowed, or if `x ** 2` overflows.
if or(lt(xxRound, xx), shr(128, x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
x := div(xxRound, b) // Set `x` to scaled `xxRound`.
// If `y` is odd:
if and(y, 1) {
let zx := mul(z, x) // Compute `z * x`.
let zxRound := add(zx, half) // Round to the nearest number.
// If `z * x` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
// Revert if `x` is non-zero.
if x {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
}
z := div(zxRound, b) // Return properly scaled `zxRound`.
}
}
}
}
}
/// @dev Returns the square root of `x`, rounded down.
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
// but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffffff, shr(r, x))))
z := shl(shr(1, r), z)
// Goal was to get `z*z*y` within a small factor of `x`. More iterations could
// get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
// We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
// That's not possible if `x < 256` but we can just verify those cases exhaustively.
// Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
// Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
// Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
// For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
// is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
// with largest error when `s = 1` and when `s = 256` or `1/256`.
// Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
// Then we can estimate `sqrt(y)` using
// `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
// There is no overflow risk here since `y < 2**136` after the first branch above.
z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If `x+1` is a perfect square, the Babylonian method cycles between
// `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
z := sub(z, lt(div(x, z), z))
}
}
/// @dev Returns the cube root of `x`, rounded down.
/// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
/// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// Makeshift lookup table to nudge the approximate log2 result.
z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
// Newton-Raphson's.
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
// Round down.
z := sub(z, lt(div(x, mul(z, z)), z))
}
}
/// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
function sqrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
z = (1 + sqrt(x)) * 10 ** 9;
z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
}
/// @solidity memory-safe-assembly
assembly {
z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
}
}
/// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
z = (1 + cbrt(x)) * 10 ** 12;
z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
}
/// @solidity memory-safe-assembly
assembly {
let p := x
for {} 1 {} {
if iszero(shr(229, p)) {
if iszero(shr(199, p)) {
p := mul(p, 100000000000000000) // 10 ** 17.
break
}
p := mul(p, 100000000) // 10 ** 8.
break
}
if iszero(shr(249, p)) { p := mul(p, 100) }
break
}
let t := mulmod(mul(z, z), z, p)
z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
}
}
/// @dev Returns `sqrt(x * y)`. Also called the geometric mean.
function mulSqrt(uint256 x, uint256 y) internal pure returns (uint256 z) {
if (x == y) return x;
uint256 p = rawMul(x, y);
if (y == rawDiv(p, x)) return sqrt(p);
for (z = saturatingMul(rawAdd(sqrt(x), 1), rawAdd(sqrt(y), 1));; z = avg(z, p)) {
if ((p = fullMulDivUnchecked(x, y, z)) >= z) break;
}
}
/// @dev Returns the factorial of `x`.
function factorial(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := 1
if iszero(lt(x, 58)) {
mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
revert(0x1c, 0x04)
}
for {} x { x := sub(x, 1) } { z := mul(z, x) }
}
}
/// @dev Returns the log2 of `x`.
/// Equivalent to computing the index of the most significant bit (MSB) of `x`.
/// Returns 0 if `x` is zero.
function log2(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000))
}
}
/// @dev Returns the log2 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log2Up(uint256 x) internal pure returns (uint256 r) {
r = log2(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(r, 1), x))
}
}
/// @dev Returns the log10 of `x`.
/// Returns 0 if `x` is zero.
function log10(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 100000000000000000000000000000000000000)) {
x := div(x, 100000000000000000000000000000000000000)
r := 38
}
if iszero(lt(x, 100000000000000000000)) {
x := div(x, 100000000000000000000)
r := add(r, 20)
}
if iszero(lt(x, 10000000000)) {
x := div(x, 10000000000)
r := add(r, 10)
}
if iszero(lt(x, 100000)) {
x := div(x, 100000)
r := add(r, 5)
}
r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
}
}
/// @dev Returns the log10 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log10Up(uint256 x) internal pure returns (uint256 r) {
r = log10(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(exp(10, r), x))
}
}
/// @dev Returns the log256 of `x`.
/// Returns 0 if `x` is zero.
function log256(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(shr(3, r), lt(0xff, shr(r, x)))
}
}
/// @dev Returns the log256 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log256Up(uint256 x) internal pure returns (uint256 r) {
r = log256(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(shl(3, r), 1), x))
}
}
/// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
/// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
/// @solidity memory-safe-assembly
assembly {
mantissa := x
if mantissa {
if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
mantissa := div(mantissa, 1000000000000000000000000000000000)
exponent := 33
}
if iszero(mod(mantissa, 10000000000000000000)) {
mantissa := div(mantissa, 10000000000000000000)
exponent := add(exponent, 19)
}
if iszero(mod(mantissa, 1000000000000)) {
mantissa := div(mantissa, 1000000000000)
exponent := add(exponent, 12)
}
if iszero(mod(mantissa, 1000000)) {
mantissa := div(mantissa, 1000000)
exponent := add(exponent, 6)
}
if iszero(mod(mantissa, 10000)) {
mantissa := div(mantissa, 10000)
exponent := add(exponent, 4)
}
if iszero(mod(mantissa, 100)) {
mantissa := div(mantissa, 100)
exponent := add(exponent, 2)
}
if iszero(mod(mantissa, 10)) {
mantissa := div(mantissa, 10)
exponent := add(exponent, 1)
}
}
}
}
/// @dev Convenience function for packing `x` into a smaller number using `sci`.
/// The `mantissa` will be in bits [7..255] (the upper 249 bits).
/// The `exponent` will be in bits [0..6] (the lower 7 bits).
/// Use `SafeCastLib` to safely ensure that the `packed` number is small
/// enough to fit in the desired unsigned integer type:
/// ```
/// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
/// ```
function packSci(uint256 x) internal pure returns (uint256 packed) {
(x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
/// @solidity memory-safe-assembly
assembly {
if shr(249, x) {
mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
revert(0x1c, 0x04)
}
packed := or(shl(7, x), packed)
}
}
/// @dev Convenience function for unpacking a packed number from `packSci`.
function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
unchecked {
unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards zero.
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = (x & y) + ((x ^ y) >> 1);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
function avg(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @dev Returns the absolute value of `x`.
function abs(int256 x) internal pure returns (uint256 z) {
unchecked {
z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(int256 x, int256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), slt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), sgt(y, x)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(uint256 x, uint256 minValue, uint256 maxValue)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
}
}
/// @dev Returns greatest common divisor of `x` and `y`.
function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
for { z := x } y {} {
let t := y
y := mod(z, y)
z := t
}
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
internal
pure
returns (uint256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
unchecked {
if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
return a - fullMulDiv(a - b, t - begin, end - begin);
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
internal
pure
returns (int256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
// forgefmt: disable-next-item
unchecked {
if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
uint256(t - begin), uint256(end - begin)));
return int256(uint256(a) - fullMulDiv(uint256(a - b),
uint256(t - begin), uint256(end - begin)));
}
}
/// @dev Returns if `x` is an even number. Some people may need this.
function isEven(uint256 x) internal pure returns (bool) {
return x & uint256(1) == uint256(0);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RAW NUMBER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(x, y)
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mod(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := smod(x, y)
}
}
/// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := addmod(x, y, d)
}
}
/// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mulmod(x, y, d)
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "none"
},
"optimizer": {
"runs": 0,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.