Verified contractPartialGPL-2.0-or-later
ProtocolFeeController
Address0x6774ca40df651c3139d25f61d3b5cdbc8aec63de
- Balance
0 ETH
- Transactions
2
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 25,666 runs
- EVM version
- cancun
- Via IR
- yes
- License
- GPL-2.0-or-later
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,697,705
- Creation transaction
- 0xf7314d5012…71150426ca
20 files
- src/ProtocolFeeController.solmain8.85 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3.1 KB
- lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol2.35 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- src/interfaces/IERC20Minimal.sol3.04 KB
- src/interfaces/IHooks.sol151 B
- src/interfaces/IPoolManager.sol1.77 KB
- src/interfaces/IProtocolFeeController.sol836 B
- src/interfaces/IProtocolFees.sol3.08 KB
- src/interfaces/IVault.sol6.51 KB
- src/interfaces/IVaultToken.sol2.92 KB
- src/libraries/CustomRevert.sol2.36 KB
- src/libraries/LPFeeLibrary.sol3.79 KB
- src/libraries/ProtocolFeeLibrary.sol2.88 KB
- src/libraries/SafeCast.sol2.06 KB
- src/libraries/math/UnsafeMath.sol1.21 KB
- src/types/BalanceDelta.sol2.36 KB
- src/types/Currency.sol5.29 KB
- src/types/PoolId.sol468 B
- src/types/PoolKey.sol1.02 KB
src/ProtocolFeeController.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity 0.8.26;
import {Ownable2Step, Ownable} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {PoolKey} from "./types/PoolKey.sol";
import {PoolId} from "./types/PoolId.sol";
import {Currency} from "./types/Currency.sol";
import {LPFeeLibrary} from "./libraries/LPFeeLibrary.sol";
import {IProtocolFeeController} from "./interfaces/IProtocolFeeController.sol";
import {IProtocolFees} from "./interfaces/IProtocolFees.sol";
import {ProtocolFeeLibrary} from "./libraries/ProtocolFeeLibrary.sol";
/// @notice ProtocolFeeController for both Pool type
contract ProtocolFeeController is IProtocolFeeController, Ownable2Step {
using ProtocolFeeLibrary for uint24;
/// @notice throw when the pool manager saved does not match the pool manager from the pool key
error InvalidPoolManager();
/// @notice throw when the default protocol fee for dynamic fee pool is invalid i.e. greater than 0.4%
error InvalidDefaultProtocolFeeForDynamicFeePool();
/// @notice throw when the protocol fee split ratio is invalid i.e. greater than 100%
error InvalidProtocolFeeSplitRatio();
/// @notice 100% in hundredths of a bip
uint256 private constant ONE_HUNDRED_PERCENT_RATIO = 1e6;
/// @notice The ratio of the protocol fee in the total fee, expressed in hundredths of a bip i.e. 1e4 is 1%
/// @dev The default value is 33% i.e. protocol fee should be 33% of the total fee
uint256 public protocolFeeSplitRatio = 33 * 1e4;
address public immutable poolManager;
/// @notice the default protocol fee for dynamic fee pool,
/// every newly created dynamic fee pool will have this default protocol fee
/// @dev 1000 = 0.1%, the initial setting is 0.03% i.e. 3bps
uint24 public defaultProtocolFeeForDynamicFeePool = 300;
event DefaultProtocolFeeForDynamicFeePoolUpdated(
uint24 oldDefaultProtocolFeeForDynamicFeePool, uint24 newDefaultProtocolFeeForDynamicFeePool
);
event ProtocolFeeSplitRatioUpdated(uint256 oldProtocolFeeSplitRatio, uint256 newProtocolFeeSplitRatio);
/// @notice emit when the protocol fee is collected
event ProtocolFeeCollected(Currency indexed currency, uint256 amount);
constructor(address _poolManager) Ownable(msg.sender) {
poolManager = _poolManager;
}
/// @notice Set the default protocol fee for dynamic fee pool, this will only impact the newly created dynamic fee pool
/// all those existing dynamic fee pools will not be affected, they will keep using the default protocol fee set at the time of creation
/// @param newDefaultProtocolFeeForDynamicFeePool 1000 = 0.1%, the initial setting is 0.03% i.e. 3bps
function setDefaultProtocolFeeForDynamicFeePool(uint24 newDefaultProtocolFeeForDynamicFeePool) external onlyOwner {
// cap the protocol fee at 0.4%, if it's over the limit we revert the tx
if (newDefaultProtocolFeeForDynamicFeePool > ProtocolFeeLibrary.MAX_PROTOCOL_FEE) {
revert InvalidDefaultProtocolFeeForDynamicFeePool();
}
uint24 oldDefaultProtocolFeeForDynamicFeePool = defaultProtocolFeeForDynamicFeePool;
defaultProtocolFeeForDynamicFeePool = newDefaultProtocolFeeForDynamicFeePool;
emit DefaultProtocolFeeForDynamicFeePoolUpdated(
oldDefaultProtocolFeeForDynamicFeePool, newDefaultProtocolFeeForDynamicFeePool
);
}
/// @notice Set the ratio of the protocol fee in the total fee
/// @param newProtocolFeeSplitRatio 30e4 would mean 30% of the total fee goes to protocol
function setProtocolFeeSplitRatio(uint256 newProtocolFeeSplitRatio) external onlyOwner {
if (newProtocolFeeSplitRatio > ONE_HUNDRED_PERCENT_RATIO) revert InvalidProtocolFeeSplitRatio();
uint256 oldProtocolFeeSplitRatio = protocolFeeSplitRatio;
protocolFeeSplitRatio = newProtocolFeeSplitRatio;
emit ProtocolFeeSplitRatioUpdated(oldProtocolFeeSplitRatio, newProtocolFeeSplitRatio);
}
/// @notice Get the LP fee based on protocolFeeSplitRatio and total fee. This is useful for FE to calculate the LP fee
/// based on user's input when initializing a static fee pool
/// warning: if protocolFee is over 0.4% based on the totalFee, then it will be capped at 0.4% which means
/// lpFee in this case will charge more lpFee than expected i.e more than "1 - protocolFeeSplitRatio"
/// @param totalFee The total fee (including lpFee and protocolFee) for the pool, expressed in hundredths of a bip
/// @return lpFee The LP fee that can be passed in as poolKey.fee, expressed in hundredths of a bip
function getLPFeeFromTotalFee(uint24 totalFee) external view returns (uint24) {
/// @dev the formula is derived from the following equation:
/// poolKey.fee = lpFee = (totalFee - protocolFee) / (1 - protocolFee)
uint256 oneDirectionProtocolFee = totalFee * protocolFeeSplitRatio / ONE_HUNDRED_PERCENT_RATIO;
if (oneDirectionProtocolFee > ProtocolFeeLibrary.MAX_PROTOCOL_FEE) {
oneDirectionProtocolFee = ProtocolFeeLibrary.MAX_PROTOCOL_FEE;
}
return uint24(
(totalFee - oneDirectionProtocolFee) * ONE_HUNDRED_PERCENT_RATIO
/ (ONE_HUNDRED_PERCENT_RATIO - oneDirectionProtocolFee)
);
}
/// @inheritdoc IProtocolFeeController
function protocolFeeForPool(PoolKey memory poolKey) external view override returns (uint24 protocolFee) {
if (address(poolKey.poolManager) != poolManager) revert InvalidPoolManager();
// calculate the protocol fee based on the predefined rule
uint256 lpFee = poolKey.fee;
if (lpFee == LPFeeLibrary.DYNAMIC_FEE_FLAG) {
/// @notice for dynamic fee pools, the default protocol fee is set separately
return _buildProtocolFee(defaultProtocolFeeForDynamicFeePool);
} else if (protocolFeeSplitRatio == 0) {
return _buildProtocolFee(0);
} else if (protocolFeeSplitRatio == ONE_HUNDRED_PERCENT_RATIO) {
return _buildProtocolFee(ProtocolFeeLibrary.MAX_PROTOCOL_FEE);
} else {
/// @notice for static fee pools, the protocol fee should be a portion of the total fee based on 'protocolFeeSplitRatio'
/// @dev the formula is derived from the following equation:
/// totalSwapFee = protocolFee + (1 - protocolFee) * lpFee = protocolFee / protocolFeeSplitRatio
uint24 oneDirectionProtocolFee = uint24(
lpFee * ONE_HUNDRED_PERCENT_RATIO
/ (
lpFee + ONE_HUNDRED_PERCENT_RATIO * ONE_HUNDRED_PERCENT_RATIO / protocolFeeSplitRatio
- ONE_HUNDRED_PERCENT_RATIO
)
);
// cap the protocol fee at 0.4%, if it's over the limit we set it to the max
if (oneDirectionProtocolFee > ProtocolFeeLibrary.MAX_PROTOCOL_FEE) {
oneDirectionProtocolFee = ProtocolFeeLibrary.MAX_PROTOCOL_FEE;
}
return _buildProtocolFee(oneDirectionProtocolFee);
}
}
/// @param fee If 1000, the protocol fee is 0.1%, cap at 0.4%
/// @return The protocol fee for both directions, the upper 12 bits are for 1->0
function _buildProtocolFee(uint24 fee) internal pure returns (uint24) {
return fee + (fee << 12);
}
/// @notice Override the default protocol fee for the pool
/// @dev this could be used for marketing campaign where PCS takes 0 protocol fee for a pool for a period
/// @param newProtocolFee 1000 = 0.1%, and max at 4000 = 0.4%. If set at 0.1%, this means 0.1% of amountIn for each swap will go to protocol
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external onlyOwner {
if (address(key.poolManager) != poolManager) revert InvalidPoolManager();
// no need to validate the protocol fee as it will be done in the pool manager
IProtocolFees(address(key.poolManager)).setProtocolFee(key, newProtocolFee);
}
/// @notice Collect the protocol fee from the pool manager
/// @param recipient The address to receive the protocol fee
/// @param currency The currency of the protocol fee
/// @param amount The amount of the protocol fee to collect, 0 means collect all
function collectProtocolFee(address recipient, Currency currency, uint256 amount) external onlyOwner {
// balance check to handle fee-on-transfer tokens
uint256 balanceBefore = currency.balanceOf(recipient);
IProtocolFees(poolManager).collectProtocolFees(recipient, currency, amount);
uint256 balanceAfter = currency.balanceOf(recipient);
emit ProtocolFeeCollected(currency, balanceAfter - balanceBefore);
}
}
lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
src/interfaces/IERC20Minimal.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for PancakeSwap
/// @notice Contains a subset of the full ERC20 interface that is used in PancakeSwap V3
interface IERC20Minimal {
/// @notice Returns the balance of a token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}
src/interfaces/IHooks.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IHooks {
function getHooksRegistrationBitmap() external view returns (uint16);
}
src/interfaces/IPoolManager.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IHooks} from "./IHooks.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {PoolId} from "../types/PoolId.sol";
import {Currency} from "../types/Currency.sol";
interface IPoolManager {
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesInitializedOutOfOrder(address currency0, address currency1);
/// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
/// or on a pool is not a dynamic fee pool.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Emitted when lp fee is updated
/// @dev The event is emitted even if the updated fee value is the same as previous one
event DynamicLPFeeUpdated(PoolId indexed id, uint24 dynamicLPFee);
/// @notice Updates lp fee for a dyanmic fee pool
/// @dev Some of the use case could be:
/// 1) when hook#beforeSwap() is called and hook call this function to update the lp fee
/// 2) For BinPool only, when hook#beforeMint() is called and hook call this function to update the lp fee
/// 3) other use case where the hook might want to on an ad-hoc basis increase/reduce lp fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
/// @notice Return PoolKey for a given PoolId
function poolIdToPoolKey(PoolId id)
external
view
returns (
Currency currency0,
Currency currency1,
IHooks hooks,
IPoolManager poolManager,
uint24 fee,
bytes32 parameters
);
}
src/interfaces/IProtocolFeeController.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
interface IProtocolFeeController {
/// @notice Get the protocol fee for a pool given the conditions of this contract
/// @param poolKey The pool key to identify the pool. The controller may want to use attributes on the pool
/// to determine the protocol fee, hence the entire key is needed.
/// @return protocolFee The pool's protocol fee, expressed in hundredths of a bip. The upper 12 bits are for 1->0
/// and the lower 12 are for 0->1. The maximum is 4000 - meaning the maximum protocol fee is 0.4%.
/// the protocolFee is taken from the input first, then the lpFee is taken from the remaining input
function protocolFeeForPool(PoolKey memory poolKey) external view returns (uint24 protocolFee);
}
src/interfaces/IProtocolFees.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {IProtocolFeeController} from "./IProtocolFeeController.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IVault} from "./IVault.sol";
interface IProtocolFees {
/// @notice Thrown when the protocol fee exceeds the upper limit.
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when calls to protocolFeeController fails or return size is not 32 bytes
error ProtocolFeeCannotBeFetched();
/// @notice Thrown when user not authorized to set or collect protocol fee
error InvalidCaller();
/// @notice Emitted when protocol fee is updated
/// @dev The event is emitted even if the updated protocolFee is the same as previous protocolFee
/// @param id The pool id for which the protocol fee is updated
/// @param protocolFee The new protocol fee value
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @notice Emitted when protocol fee controller is updated
/// @param protocolFeeController The new protocol fee controller
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Given a currency address, returns the protocol fees accrued in that currency
/// @param currency The currency to check
/// @return amount The amount of protocol fees accrued in the given currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Returns the current protocol fee controller address
/// @return IProtocolFeeController The currency protocol fee controller
function protocolFeeController() external view returns (IProtocolFeeController);
/// @notice Sets the protocol's swap fee for the given pool
/// @param key The pool key for which to set the protocol fee
/// @param newProtocolFee The new protocol fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Update the protocol fee controller, called by the owner
/// @param controller The new protocol fee controller to be set
function setProtocolFeeController(IProtocolFeeController controller) external;
/// @notice Collects the protocol fee accrued in the given currency, called by the owner or the protocol fee controller
/// @dev This will revert if vault is locked
/// @param recipient The address to which the protocol fees should be sent
/// @param currency The currency in which to collect the protocol fees
/// @param amount The amount of protocol fees to collect
/// @return amountCollected The amount of protocol fees actually collected
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the vault where the protocol fees are safely stored
/// @return IVault The address of the vault
function vault() external view returns (IVault);
}
src/interfaces/IVault.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IVaultToken} from "./IVaultToken.sol";
interface IVault is IVaultToken {
event AppRegistered(address indexed app);
/// @notice Thrown when a app is not registered
error AppUnregistered();
/// @notice Thrown when a currency is not netted out after a lock
error CurrencyNotSettled();
/// @notice Thrown when there is already a locker
/// @param locker The address of the current locker
error LockerAlreadySet(address locker);
/// @notice Thrown when passing in msg.value for non-native currency
error SettleNonNativeCurrencyWithValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Thrown when there is no locker
error NoLocker();
/// @notice Thrown when collectFee is attempted on a token that is synced.
error FeeCurrencySynced();
function isAppRegistered(address app) external returns (bool);
/// @notice Returns the reserves for a a given pool type and currency
function reservesOfApp(address app, Currency currency) external view returns (uint256);
/// @notice register an app so that it can perform accounting base on vault
function registerApp(address app) external;
/// @notice Returns the locker who is locking the vault
function getLocker() external view returns (address locker);
/// @notice Returns the reserve and its amount that is currently being stored in trnasient storage
function getVaultReserve() external view returns (Currency, uint256);
/// @notice Returns lock data
function getUnsettledDeltasCount() external view returns (uint256 count);
/// @notice Get the current delta for a locker in the given currency
/// @param currency The currency for which to lookup the delta
function currencyDelta(address settler, Currency currency) external view returns (int256);
/// @notice All operations go through this function
/// @param data Any data to pass to the callback, via `ILockCallback(msg.sender).lockCallback(data)`
/// @return The data returned by the call to `ILockCallback(msg.sender).lockCallback(data)`
function lock(bytes calldata data) external returns (bytes memory);
/// @notice Called by registered app to account for a change in the pool balance,
/// convenient for AMM pool manager, typically after modifyLiquidity, swap, donate,
/// include the case where hookDelta is involved
/// @param currency0 The PoolKey currency0 to update
/// @param currency1 The PoolKey currency1 to update
/// @param delta The change in the pool's balance
/// @param settler The address whose delta will be updated
/// @param hookDelta The change in the pool's balance from hook
/// @param hook The address whose hookDelta will be updated
function accountAppBalanceDelta(
Currency currency0,
Currency currency1,
BalanceDelta delta,
address settler,
BalanceDelta hookDelta,
address hook
) external;
/// @notice Called by registered app to account for a change in the pool balance,
/// convenient for AMM pool manager, typically after modifyLiquidity, swap, donate
/// @param currency0 The PoolKey currency0 to update
/// @param currency1 The PoolKey currency1 to update
/// @param delta The change in the pool's balance
/// @param settler The address whose delta will be updated
function accountAppBalanceDelta(Currency currency0, Currency currency1, BalanceDelta delta, address settler)
external;
/// @notice This works as a general accounting mechanism for non-dex app
/// @param currency The currency to update
/// @param delta The change in the balance
/// @param settler The address whose delta will be updated
function accountAppBalanceDelta(Currency currency, int128 delta, address settler) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
function take(Currency currency, address to, uint256 amount) external;
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(Currency token0) external;
/// @notice Called by the user to pay what is owed
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retreivable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(Currency currency, uint256 amount) external;
/// @notice Called by app to collect any fee related
/// @dev no restriction on caller, underflow happen if caller collect more than the reserve
function collectFee(Currency currency, uint256 amount, address recipient) external;
/// @notice Called by the user to store surplus tokens in the vault
function mint(address to, Currency currency, uint256 amount) external;
/// @notice Called by the user to use surplus tokens for payment settlement
function burn(address from, Currency currency, uint256 amount) external;
}
src/interfaces/IVaultToken.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IPoolManager} from "./IPoolManager.sol";
import {Currency} from "../types/Currency.sol";
interface IVaultToken {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, Currency indexed currency, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, Currency indexed currency, uint256 amount);
/// @notice get the amount of owner's surplus token in vault
/// @param owner The address you want to query the balance of
/// @param currency The currency you want to query the balance of
/// @return balance The balance of the specified address
function balanceOf(address owner, Currency currency) external view returns (uint256 balance);
/// @notice get the amount that owner has authorized for spender to use
/// @param owner The address of the owner
/// @param spender The address who is allowed to spend the owner's token
/// @param currency The currency the spender is allowed to spend
/// @return amount The amount of token the spender is allowed to spend
function allowance(address owner, address spender, Currency currency) external view returns (uint256 amount);
/// @notice approve spender for using user's token
/// @param spender The address msg.sender is approving to spend the his token
/// @param currency The currency the spender is allowed to spend
/// @param amount The amount of token the spender is allowed to spend
/// @return bool Whether the approval was successful or not
function approve(address spender, Currency currency, uint256 amount) external returns (bool);
/// @notice transfer msg.sender's token to someone else
/// @param to The address to transfer the token to
/// @param currency The currency to transfer
/// @param amount The amount of token to transfer
/// @return bool Whether the transfer was successful or not
function transfer(address to, Currency currency, uint256 amount) external returns (bool);
/// @notice transfer from address's token on behalf of him
/// @param from The address to transfer the token from
/// @param to The address to transfer the token to
/// @param currency The currency to transfer
/// @param amount The amount of token to transfer
/// @return bool Whether the transfer was successful or not
function transferFrom(address from, address to, Currency currency, uint256 amount) external returns (bool);
}
src/libraries/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
src/libraries/LPFeeLibrary.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;
/// @notice Library for handling lp fee setting from `PoolKey.fee`
/// It can be either static or dynamic, and upper 4 bits are used to store the flag:
/// 1. if the flag is set, then the fee is dynamic, it can be set and updated by hook
/// 2. otherwise if the flag is not set, then the fee is static, and the lower 20 bits are used to store the fee
library LPFeeLibrary {
using LPFeeLibrary for uint24;
/// @notice Thrown when the static/dynamic fee on a pool exceeds 100%.
error LPFeeTooLarge(uint24 fee);
/// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
uint24 public constant OVERRIDE_MASK = 0xBFFFFF;
/// @notice a dynamic fee pool must have exactly same value for fee field
uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;
/// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
// only dynamic-fee pools can return a fee via the beforeSwap hook
uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;
/// @notice the fee is represented in hundredths of a bip
/// max fee varies between different pool types i.e. it's 100% for cl pool and 10% for bin pool
uint24 public constant ONE_HUNDRED_PERCENT_FEE = 1_000_000;
uint24 public constant TEN_PERCENT_FEE = 100_000;
/// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
/// @param self The fee to check
/// @return bool True of the fee is dynamic
function isDynamicLPFee(uint24 self) internal pure returns (bool) {
return self == DYNAMIC_FEE_FLAG;
}
/// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
/// @param self The fee to validate
/// @param maxFee The maximum fee allowed for the pool
function validate(uint24 self, uint24 maxFee) internal pure {
if (self > maxFee) revert LPFeeTooLarge(self);
}
/// @notice gets the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
/// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
/// @param self The fee to get the initial LP from
/// @return initialFee 0 if the fee is dynamic, otherwise the original value
function getInitialLPFee(uint24 self) internal pure returns (uint24 initialFee) {
// the initial fee for a dynamic fee pool is 0
if (self.isDynamicLPFee()) return 0;
initialFee = self;
}
/// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
/// @param self The fee to check
/// @return bool True of the fee has the override flag set
function isOverride(uint24 self) internal pure returns (bool) {
return self & OVERRIDE_FEE_FLAG != 0;
}
/// @notice returns a fee with the override flag removed
/// @param self The fee to remove the override flag from
/// @return fee The fee without the override flag set
function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
return self & OVERRIDE_MASK;
}
/// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
/// @param self The fee to remove the override flag from, and then validate
/// @param maxFee The maximum fee allowed for the pool
/// @return fee The fee without the override flag set (if valid)
function removeOverrideAndValidate(uint24 self, uint24 maxFee) internal pure returns (uint24) {
uint24 fee = self.removeOverrideFlag();
fee.validate(maxFee);
return fee;
}
}
src/libraries/ProtocolFeeLibrary.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;
import "./math/UnsafeMath.sol";
library ProtocolFeeLibrary {
/// @dev Increasing these values could lead to overflow in Pool.swap
/// @notice Max protocol fee is 0.4% (4000 pips)
uint16 public constant MAX_PROTOCOL_FEE = 4000;
/// @notice Thresholds used for optimized bounds checks on protocol fees
uint24 internal constant FEE_0_THRESHOLD = 4001;
uint24 internal constant FEE_1_THRESHOLD = 4001 << 12;
/// @notice the protocol fee is represented in hundredths of a bip
uint256 internal constant PIPS_DENOMINATOR = 1_000_000;
/// @notice Get the fee taken when swap token0 for token1
/// @param self The composite protocol fee to get the single direction fee from
/// @return The fee taken when swapping token0 for token1
function getZeroForOneFee(uint24 self) internal pure returns (uint16) {
return uint16(self & 0xfff);
}
/// @notice Get the fee taken when swap token1 for token0
/// @param self The composite protocol fee to get the single direction fee from
/// @return The fee taken when swapping token1 for token0
function getOneForZeroFee(uint24 self) internal pure returns (uint16) {
return uint16(self >> 12);
}
/// @notice Validate that the protocol fee is within bounds
/// @param self The composite protocol fee to validate
/// @return valid True if the fee is within bounds
function validate(uint24 self) internal pure returns (bool valid) {
// Equivalent to: getZeroForOneFee(self) <= MAX_PROTOCOL_FEE && getOneForZeroFee(self) <= MAX_PROTOCOL_FEE
assembly ("memory-safe") {
let isZeroForOneFeeOk := lt(and(self, 0xfff), FEE_0_THRESHOLD)
let isOneForZeroFeeOk := lt(and(self, 0xfff000), FEE_1_THRESHOLD)
valid := and(isZeroForOneFeeOk, isOneForZeroFeeOk)
}
}
/// @notice The protocol fee is taken from the input amount first and then the LP fee is taken from the remaining
// Equivalent to protocolFee + lpFee(1_000_000 - protocolFee) / 1_000_000 (rounded up)
/// Also note the swap fee is capped at 1_000_000 (100%) for cl pool and 100_000 (10%) for bin pool
/// @param self The single direction protocol fee to calculate the swap fee from
/// @param lpFee The LP fee to calculate the swap fee from
/// @return swapFee The composite swap fee
function calculateSwapFee(uint16 self, uint24 lpFee) internal pure returns (uint24 swapFee) {
// protocolFee + lpFee - (protocolFee * lpFee / 1_000_000)
assembly ("memory-safe") {
self := and(self, 0xfff)
lpFee := and(lpFee, 0xffffff)
let numerator := mul(self, lpFee)
swapFee := sub(add(self, lpFee), div(numerator, PIPS_DENOMINATOR))
}
}
}
src/libraries/SafeCast.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
error SafeCastOverflow();
function _revertOverflow() private pure {
assembly ("memory-safe") {
// Store the function selector of `SafeCastOverflow()`.
mstore(0x00, 0x93dafdf1)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
}
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) _revertOverflow();
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) _revertOverflow();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) _revertOverflow();
}
/// @notice Cast a int256 to a uint256, revert on overflow
/// @param x The int256 to be casted
/// @return y The casted integer, now type uint256
function toUint256(int256 x) internal pure returns (uint256 y) {
if (x < 0) _revertOverflow();
y = uint256(x);
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) _revertOverflow();
return int128(int256(x));
}
}
src/libraries/math/UnsafeMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;
/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
/// @notice Returns ceil(x / y)
/// @dev division by 0 will return 0, and should be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly ("memory-safe") {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
/// @notice Calculates floor(a×b÷denominator)
/// @dev division by 0 will return 0, and should be checked externally
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result, floor(a×b÷denominator)
function simpleMulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
assembly ("memory-safe") {
result := div(mul(a, b), denominator)
}
}
}
src/types/BalanceDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice Constant for a BalanceDelta of zero value
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}
src/types/Currency.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
using CurrencyLibrary for Currency;
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant NATIVE = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isNative()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isNative()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isNative()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isNative(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(NATIVE);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}
src/types/PoolId.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xc0 represents the total size of the poolKey struct (6 slots of 32 bytes)
poolId := keccak256(poolKey, 0xc0)
}
}
}
src/types/PoolKey.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The hooks of the pool, won't have a general interface because hooks interface vary on pool type
IHooks hooks;
/// @notice The pool manager of the pool
IPoolManager poolManager;
/// @notice The pool lp fee, capped at 1_000_000. If the pool has a dynamic fee then it must be exactly equal to 0x800000
uint24 fee;
/// @notice Hooks callback and pool specific parameters, i.e. tickSpacing for CL, binStep for bin
bytes32 parameters;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "none"
},
"libraries": {},
"optimizer": {
"runs": 25666,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/=lib/openzeppelin-contracts/",
"ds-test/=lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/forge-gas-snapshot/src/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"pancake-create3-factory/=lib/pancake-create3-factory/",
"solmate/=lib/solmate/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.