Source Code
Latest 25 from a total of 237 transactions
| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
| Claim Tokens | 41142113 | 3 days ago | IN | 0 ETH | 0.0000053 | ||||
| Claim Tokens | 40985761 | 7 days ago | IN | 0 ETH | 0.00000168 | ||||
| Claim Tokens | 40965000 | 7 days ago | IN | 0 ETH | 0.00000039 | ||||
| Claim Tokens | 40751130 | 12 days ago | IN | 0 ETH | 0.00000038 | ||||
| Claim Tokens | 39608595 | 39 days ago | IN | 0 ETH | 0.00000144 | ||||
| Claim Tokens | 39524481 | 41 days ago | IN | 0 ETH | 0.00000008 | ||||
| Claim Tokens | 39417497 | 43 days ago | IN | 0 ETH | 0.00000146 | ||||
| Claim Tokens | 39241409 | 47 days ago | IN | 0 ETH | 0.00000288 | ||||
| Claim Tokens | 39033886 | 52 days ago | IN | 0 ETH | 0.00000166 | ||||
| Claim Tokens | 38864373 | 56 days ago | IN | 0 ETH | 0.00000955 | ||||
| Claim Tokens | 38770103 | 58 days ago | IN | 0 ETH | 0.00000127 | ||||
| Claim Tokens | 38738106 | 59 days ago | IN | 0 ETH | 0.0000005 | ||||
| Claim Tokens | 37892070 | 79 days ago | IN | 0 ETH | 0.00000115 | ||||
| Claim Tokens | 37422738 | 89 days ago | IN | 0 ETH | 0.00001358 | ||||
| Claim Tokens | 37386340 | 90 days ago | IN | 0 ETH | 0.00003437 | ||||
| Claim Tokens | 37181202 | 95 days ago | IN | 0 ETH | 0.00000427 | ||||
| Claim Tokens | 37181038 | 95 days ago | IN | 0 ETH | 0.00000913 | ||||
| Claim Tokens | 37168730 | 95 days ago | IN | 0 ETH | 0.0000003 | ||||
| Claim Tokens | 37118771 | 96 days ago | IN | 0 ETH | 0.0000225 | ||||
| Claim Tokens | 37093118 | 97 days ago | IN | 0 ETH | 0.00000465 | ||||
| Claim Tokens | 37045342 | 98 days ago | IN | 0 ETH | 0.00000001 | ||||
| Claim Tokens | 37045332 | 98 days ago | IN | 0 ETH | 0.00000006 | ||||
| Claim Tokens | 36995862 | 99 days ago | IN | 0 ETH | 0.00000008 | ||||
| Claim Tokens | 36973848 | 100 days ago | IN | 0 ETH | 0.00000107 | ||||
| Claim Tokens | 36934605 | 101 days ago | IN | 0 ETH | 0.0000005 |
Latest 25 internal transactions (View All)
| Parent Transaction Hash | Block | From | To | |||
|---|---|---|---|---|---|---|
| 41142113 | 3 days ago | 0.00040952 ETH | ||||
| 41142113 | 3 days ago | 0.00040952 ETH | ||||
| 41142113 | 3 days ago | 0.00000157 ETH | ||||
| 41142113 | 3 days ago | 0.00000157 ETH | ||||
| 41142113 | 3 days ago | 0.00002784 ETH | ||||
| 41142113 | 3 days ago | 0.00002784 ETH | ||||
| 41142113 | 3 days ago | 0.00035305 ETH | ||||
| 41142113 | 3 days ago | 0.00035305 ETH | ||||
| 41142113 | 3 days ago | 0.0002015 ETH | ||||
| 41142113 | 3 days ago | 0.0002015 ETH | ||||
| 40985761 | 7 days ago | 0.00099607 ETH | ||||
| 40985761 | 7 days ago | 0.00099607 ETH | ||||
| 40985761 | 7 days ago | 0.00033812 ETH | ||||
| 40985761 | 7 days ago | 0.00033812 ETH | ||||
| 40965000 | 7 days ago | 0.00001078 ETH | ||||
| 40965000 | 7 days ago | 0.00001078 ETH | ||||
| 39524481 | 41 days ago | 0.00000734 ETH | ||||
| 39524481 | 41 days ago | 0.00000734 ETH | ||||
| 39417497 | 43 days ago | 0.00000035 ETH | ||||
| 39417497 | 43 days ago | 0.00000035 ETH | ||||
| 39241409 | 47 days ago | 0.00000363 ETH | ||||
| 39241409 | 47 days ago | 0.00000363 ETH | ||||
| 39241409 | 47 days ago | 0.00000948 ETH | ||||
| 39241409 | 47 days ago | 0.00000948 ETH | ||||
| 39241409 | 47 days ago | 0.00000163 ETH |
Cross-Chain Transactions
Loading...
Loading
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0xF2972fBD...2641f08bD The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Name:
ReferralEscrow
Compiler Version
v0.8.30+commit.73712a01
Optimization Enabled:
Yes with 10 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { BalanceDelta } from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import { Currency } from "@uniswap/v4-core/src/types/Currency.sol";
import { IHooks } from "@uniswap/v4-core/src/libraries/Hooks.sol";
import { IPoolManager } from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { IPoolSwap } from "../interfaces/IPoolSwap.sol";
import { SwapParams } from "@uniswap/v4-core/src/types/PoolOperation.sol";
import { IPhiEth } from "../interfaces/IPhiEth.sol";
import { IReferralEscrow } from "../interfaces/IReferralEscrow.sol";
import { IPhiEthFactory } from "../interfaces/IPhiEthFactory.sol";
import { IBoardManager } from "../interfaces/IBoardManager.sol";
/**
* When a user referrers someone that then actions a swap, their address is passed in the `hookData`. This
* user will then receive a referral fee of the unspecified token amount. This amount will be moved to this
* escrow contract to be claimed at a later time.
* @dev Based on: https://github.com/flayerlabs
*/
contract ReferralEscrow is Ownable2Step, IReferralEscrow {
using SafeERC20 for IERC20;
address boardHook;
IPoolSwap public poolSwap;
IPhiEthFactory public phiEthFactory;
IBoardManager public boardManager;
// Struct to hold token swap info to reduce stack variables
struct SwapInfo {
address token;
address nativeToken;
uint256 amount;
uint256 amountOut;
}
/// Mapping to track token allocations by user and token
mapping(address _user => mapping(address _token => uint256 _amount)) public allocations;
/**
* Constructor to initialize the PoolSwap contract address.
* @param _boardHook The address of the BoardHook contract
* @param _phiEthFactory The address of the PhiEth manager contract
* @param _boardManager The address of the BoardManager contract
* @param _poolSwap The new address that will handle pool swaps
* @param _protocolOwner The address of the protocol owner
*/
constructor(
address _boardHook,
address _phiEthFactory,
address _boardManager,
address _poolSwap,
address _protocolOwner
)
Ownable(_protocolOwner)
{
if (_boardHook == address(0)) revert InvalidAddress();
if (_phiEthFactory == address(0)) revert InvalidAddress();
if (_boardManager == address(0)) revert InvalidAddress();
if (_poolSwap == address(0)) revert InvalidAddress();
if (_protocolOwner == address(0)) revert InvalidAddress();
boardHook = _boardHook;
phiEthFactory = IPhiEthFactory(_phiEthFactory);
boardManager = IBoardManager(_boardManager);
poolSwap = IPoolSwap(_poolSwap);
}
/**
* Function to update the PoolSwap contract address (only owner can call this).
*
* @param _poolSwap The new address that will handle pool swaps
*/
function setPoolSwap(address _poolSwap) external onlyOwner {
if (_poolSwap == address(0)) revert InvalidAddress();
poolSwap = IPoolSwap(_poolSwap);
}
/**
* Function to assign tokens to a user with a PoolId included in the event.
*
* @dev Only the BoardHook contract can make this call.
*
* @param _poolId The PoolId that generated referral fees
* @param _user The user that received the referral fees
* @param _token The token that the fees are paid in
* @param _amount The amount of fees granted to the user
*/
function assignTokens(PoolId _poolId, address _user, address _token, uint256 _amount) external {
if (msg.sender != boardHook) revert Unauthorized();
// If no amount is passed, then we have nothing to process
if (_amount == 0) return;
allocations[_user][_token] += _amount;
emit TokensAssigned(_poolId, _user, _token, _amount);
}
/**
* Function for a user to claim tokens across multiple token addresses.
*
* @param _tokens The tokens to be claimed by the caller
*/
function claimTokens(address[] calldata _tokens, address payable _recipient) external {
if (_recipient == address(0)) revert InvalidAddress();
address token;
uint256 amount;
for (uint256 i; i < _tokens.length; ++i) {
token = _tokens[i];
amount = allocations[msg.sender][token];
// If there is nothing to claim, skip next steps
if (amount == 0) continue;
// Update allocation before transferring to prevent reentrancy attacks
allocations[msg.sender][token] = 0;
// If we are claiming the native token, then we can unwrap the flETH to ETH
if (phiEthFactory.isPhiEth(token)) {
// Withdraw the PhiEth and transfer the ETH to the caller
IPhiEth(token).withdraw(amount);
(bool _sent,) = _recipient.call{ value: amount }("");
require(_sent, "ETH Transfer Failed");
}
// Otherwise, just transfer the token directly to the user
else {
SafeERC20.safeTransfer(IERC20(address(token)), _recipient, amount);
}
emit TokensClaimed(msg.sender, _recipient, token, amount);
}
}
// Helper function to perform a single token swap
function _performSwap(SwapInfo memory info, uint160 sqrtPriceLimitX96) private returns (uint256) {
if (phiEthFactory.isPhiEth(info.token)) {
return info.amount; // For native tokens, just return the amount
}
// in case the token is not a PhiEth, we need to perform a swap
// Provide the swap contract with sufficient allocation for the swap
IERC20(info.token).approve(address(poolSwap), info.amount);
info.nativeToken = boardManager.boardToPhiEth(info.token);
if (info.nativeToken == address(0)) revert InvalidBoardToken();
// Perform the swap using PoolSwap contract with corresponding sqrtPriceX96Limit
bool flipped = info.token < info.nativeToken;
BalanceDelta delta = poolSwap.swap({
_key: PoolKey({
currency0: Currency.wrap(flipped ? info.token : info.nativeToken),
currency1: Currency.wrap(flipped ? info.nativeToken : info.token),
fee: 0,
hooks: IHooks(boardHook),
tickSpacing: 60
}),
_params: SwapParams({
zeroForOne: flipped,
amountSpecified: -int256(info.amount),
sqrtPriceLimitX96: sqrtPriceLimitX96
})
});
uint256 actualConsumed = uint256(-int256(flipped ? delta.amount0() : delta.amount1()));
uint256 unspent = info.amount - actualConsumed;
if (unspent > 0) {
allocations[msg.sender][info.token] += unspent;
}
// Get the amount of tokens received from the swap
return uint128(flipped ? delta.amount1() : delta.amount0());
}
/**
* Function for a user to claim and swap tokens across multiple token addresses.
*
* @param _tokens The tokens that are being claimed and swapped
* @param _sqrtPriceX96Limits The respective token's sqrtPriceX96 limit
*/
function claimBoardAndSwap(
address[] calldata _tokens,
uint160[] calldata _sqrtPriceX96Limits,
address payable _recipient
)
external
{
// Ensure that we have a limit for each token
uint256 tokensLength = _tokens.length;
if (tokensLength != _sqrtPriceX96Limits.length) revert MismatchedTokensAndLimits();
// Track amounts per native token using arrays
address[] memory nativeTokens = new address[](tokensLength);
uint256[] memory amounts = new uint256[](tokensLength);
uint256 nativeTokenCount = 0;
// Process all tokens
for (uint256 i; i < tokensLength; ++i) {
SwapInfo memory info;
info.token = _tokens[i];
info.amount = allocations[msg.sender][info.token];
// If no tokens are available, skip the claim
if (info.amount == 0) continue;
// Update allocation before transferring to prevent reentrancy attacks
allocations[msg.sender][info.token] = 0;
// Get the output amount from the swap
info.amountOut = _performSwap(info, _sqrtPriceX96Limits[i]);
// If this is a native PhiETH token
if (phiEthFactory.isPhiEth(info.token)) {
info.nativeToken = info.token;
}
// Find or add the native token in our tracking arrays
bool foundExisting = false;
for (uint256 j = 0; j < nativeTokenCount; j++) {
if (nativeTokens[j] == info.nativeToken) {
// Add to existing amount
amounts[j] += info.amountOut;
foundExisting = true;
break;
}
}
// If this is a new native token, add it to our arrays
if (!foundExisting) {
nativeTokens[nativeTokenCount] = info.nativeToken;
amounts[nativeTokenCount] = info.amountOut;
nativeTokenCount++;
}
emit TokensClaimed(msg.sender, _recipient, info.token, info.amount);
if (!phiEthFactory.isPhiEth(info.token)) {
emit TokensSwapped(msg.sender, info.token, info.amount, info.amountOut);
}
}
// Process withdrawals
_processWithdrawals(nativeTokens, amounts, nativeTokenCount, _recipient);
}
// Helper function to process all withdrawals
function _processWithdrawals(
address[] memory nativeTokens,
uint256[] memory amounts,
uint256 nativeTokenCount,
address payable recipient
)
private
{
uint256 totalEthSent = 0;
// Process each native token separately
for (uint256 i = 0; i < nativeTokenCount; i++) {
address nativeToken = nativeTokens[i];
uint256 amountToWithdraw = amounts[i];
if (amountToWithdraw > 0) {
// Withdraw the PhiEth for this specific native token
IPhiEth(nativeToken).withdraw(amountToWithdraw);
totalEthSent += amountToWithdraw;
}
}
// Send all the ETH to the recipient in one transaction
if (totalEthSent > 0) {
(bool _sent,) = recipient.call{ value: totalEthSent }("");
require(_sent, "ETH Transfer Failed");
}
}
/**
* Allows the contract to receive ETH from the phiEth withdrawal.
*/
receive() external payable { }
}// 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.
*
* 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);
}
}// 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);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}// 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 A BalanceDelta of 0
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)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/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 {
/// @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 ADDRESS_ZERO = 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.isAddressZero()) {
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.isAddressZero()) {
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.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {SafeCast} from "./SafeCast.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
library Hooks {
using LPFeeLibrary for uint24;
using Hooks for IHooks;
using SafeCast for int256;
using BeforeSwapDeltaLibrary for BeforeSwapDelta;
using ParseBytes for bytes;
using CustomRevert for bytes4;
uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);
uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;
uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;
uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;
uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;
uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;
uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;
uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;
uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;
uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;
uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;
uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;
uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;
struct Permissions {
bool beforeInitialize;
bool afterInitialize;
bool beforeAddLiquidity;
bool afterAddLiquidity;
bool beforeRemoveLiquidity;
bool afterRemoveLiquidity;
bool beforeSwap;
bool afterSwap;
bool beforeDonate;
bool afterDonate;
bool beforeSwapReturnDelta;
bool afterSwapReturnDelta;
bool afterAddLiquidityReturnDelta;
bool afterRemoveLiquidityReturnDelta;
}
/// @notice Thrown if the address will not lead to the specified hook calls being called
/// @param hooks The address of the hooks contract
error HookAddressNotValid(address hooks);
/// @notice Hook did not return its selector
error InvalidHookResponse();
/// @notice Additional context for ERC-7751 wrapped error when a hook call fails
error HookCallFailed();
/// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa
error HookDeltaExceedsSwapAmount();
/// @notice Utility function intended to be used in hook constructors to ensure
/// the deployed hooks address causes the intended hooks to be called
/// @param permissions The hooks that are intended to be called
/// @dev permissions param is memory as the function will be called from constructors
function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {
if (
permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)
|| permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)
|| permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)
|| permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)
|| permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)
|| permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
|| permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)
|| permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)
|| permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)
|| permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)
|| permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
|| permissions.afterRemoveLiquidityReturnDelta
!= self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) {
HookAddressNotValid.selector.revertWith(address(self));
}
}
/// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address
/// @param self The hook to verify
/// @param fee The fee of the pool the hook is used with
/// @return bool True if the hook address is valid
function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {
// The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag
if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))
{
return false;
}
if (
!self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
&& self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) return false;
// If there is no hook contract set, then fee cannot be dynamic
// If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee
return address(self) == address(0)
? !fee.isDynamicFee()
: (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());
}
/// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta
/// @return result The complete data returned by the hook
function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
bool success;
assembly ("memory-safe") {
success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
}
// Revert with FailedHookCall, containing any error message to bubble up
if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);
// The call was successful, fetch the returned data
assembly ("memory-safe") {
// allocate result byte array from the free memory pointer
result := mload(0x40)
// store new free memory pointer at the end of the array padded to 32 bytes
mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
// store length in memory
mstore(result, returndatasize())
// copy return data to result
returndatacopy(add(result, 0x20), 0, returndatasize())
}
// Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
InvalidHookResponse.selector.revertWith();
}
}
/// @notice performs a hook call using the given calldata on the given hook
/// @return int256 The delta returned by the hook
function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {
bytes memory result = callHook(self, data);
// If this hook wasn't meant to return something, default to 0 delta
if (!parseReturn) return 0;
// A length of 64 bytes is required to return a bytes4, and a 32 byte delta
if (result.length != 64) InvalidHookResponse.selector.revertWith();
return result.parseReturnDelta();
}
/// @notice modifier to prevent calling a hook if they initiated the action
modifier noSelfCall(IHooks self) {
if (msg.sender != address(self)) {
_;
}
}
/// @notice calls beforeInitialize hook if permissioned and validates return value
function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {
if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));
}
}
/// @notice calls afterInitialize hook if permissioned and validates return value
function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));
}
}
/// @notice calls beforeModifyLiquidity hook if permissioned and validates return value
function beforeModifyLiquidity(
IHooks self,
PoolKey memory key,
ModifyLiquidityParams memory params,
bytes calldata hookData
) internal noSelfCall(self) {
if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));
} else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));
}
}
/// @notice calls afterModifyLiquidity hook if permissioned and validates return value
function afterModifyLiquidity(
IHooks self,
PoolKey memory key,
ModifyLiquidityParams memory params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);
callerDelta = delta;
if (params.liquidityDelta > 0) {
if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
} else {
if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
}
}
/// @notice calls beforeSwap hook if permissioned and validates return value
function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData)
internal
returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)
{
amountToSwap = params.amountSpecified;
if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);
if (self.hasPermission(BEFORE_SWAP_FLAG)) {
bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));
// A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
if (result.length != 96) InvalidHookResponse.selector.revertWith();
// dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
// is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();
// skip this logic for the case where the hook return is 0
if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());
// any return in unspecified is passed to the afterSwap hook for handling
int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();
// Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
if (hookDeltaSpecified != 0) {
bool exactInput = amountToSwap < 0;
amountToSwap += hookDeltaSpecified;
if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
HookDeltaExceedsSwapAmount.selector.revertWith();
}
}
}
}
}
/// @notice calls afterSwap hook if permissioned and validates return value
function afterSwap(
IHooks self,
PoolKey memory key,
SwapParams memory params,
BalanceDelta swapDelta,
bytes calldata hookData,
BeforeSwapDelta beforeSwapHookReturn
) internal returns (BalanceDelta, BalanceDelta) {
if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);
int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();
int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();
if (self.hasPermission(AFTER_SWAP_FLAG)) {
hookDeltaUnspecified += self.callHookWithReturnDelta(
abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),
self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
).toInt128();
}
BalanceDelta hookDelta;
if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
: toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);
// the caller has to pay for (or receive) the hook's delta
swapDelta = swapDelta - hookDelta;
}
return (swapDelta, hookDelta);
}
/// @notice calls beforeDonate hook if permissioned and validates return value
function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(BEFORE_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
/// @notice calls afterDonate hook if permissioned and validates return value
function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
return uint160(address(self)) & flag != 0;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error CurrencyNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error ManagerLocked();
/// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
error TickSpacingTooLarge(int24 tickSpacing);
/// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
error TickSpacingTooSmall(int24 tickSpacing);
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(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 that does not have a dynamic swap fee.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param hooks The hooks contract address for the pool, or address(0) if none
/// @param sqrtPriceX96 The price of the pool on initialization
/// @param tick The initial tick of the pool corresponding to the initialized price
event Initialize(
PoolId indexed id,
Currency indexed currency0,
Currency indexed currency1,
uint24 fee,
int24 tickSpacing,
IHooks hooks,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted when a liquidity position is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param sqrtPriceX96 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 the price of the pool after the swap
/// @param fee The swap fee in hundredths of a bip
event Swap(
PoolId indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint24 fee
);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
/// @param sqrtPriceX96 The initial square root price
/// @return tick The initial tick of the pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
/// @notice Modify the liquidity for the given pool
/// @dev Poke by calling with a zero liquidityDelta
/// @param key The pool to modify liquidity in
/// @param params The parameters for modifying the liquidity
/// @param hookData The data to pass through to the add/removeLiquidity hooks
/// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
/// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
/// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
/// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
/// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
external
returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @param hookData The data to pass through to the swap hooks
/// @return swapDelta The balance delta of the address swapping
/// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
/// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
/// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
/// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
/// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
/// Donors should keep this in mind when designing donation mechanisms.
/// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
/// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
/// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
/// Read the comments in `Pool.swap()` for more information about this.
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData The data to pass through to the donate hooks
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
external
returns (BalanceDelta);
/// @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 currency) 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
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(Currency currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
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-retrievable, 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 the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
/// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The key of the pool to update dynamic LP fees for
/// @param newDynamicLPFee The new dynamic pool LP fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}// 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 {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.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 pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { BalanceDelta } from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import { IPoolManager } from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { SwapParams } from "@uniswap/v4-core/src/types/PoolOperation.sol"; // 追加
/**
* @title IPoolSwap
* @notice Interface for the PoolSwap contract that handles swaps against Uniswap V4 pools
*/
interface IPoolSwap {
/**
* @notice The Uniswap V4 PoolManager contract
* @return The address of the PoolManager
*/
function manager() external view returns (IPoolManager);
/**
* @notice Actions a swap using the SwapParams provided against the PoolKey without a referrer
* @param _key The PoolKey to swap against
* @param _params The parameters for the swap
* @return The BalanceDelta of the swap
*/
function swap(
PoolKey memory _key,
SwapParams memory _params // IPoolManager.SwapParams → SwapParams に変更
)
external
payable
returns (BalanceDelta);
/**
* @notice Actions a swap using the SwapParams provided against the PoolKey with a referrer
* @param _key The PoolKey to swap against
* @param _params The parameters for the swap
* @param _referrer The referrer of the swap
* @param _proof Proof data for the swap
* @param _maxAllocation The maximum allocation for the swap
* @return delta_ The BalanceDelta of the swap
*/
function swap(
PoolKey memory _key,
SwapParams memory _params, // IPoolManager.SwapParams → SwapParams に変更
address _referrer,
bytes32[] memory _proof,
uint256 _maxAllocation
)
external
payable
returns (BalanceDelta delta_);
/**
* @notice Callback function for unlocking operations
* @param rawData The raw callback data
* @return The encoded result data
*/
function unlockCallback(bytes calldata rawData) external returns (bytes memory);
/**
* @notice Returns the message sender from the Locker
* @return The address of the message sender
*/
function msgSender() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IBasePhiEthStrategy } from "./IBasePhiEthStrategy.sol";
/**
* @title IPhiEth
* @notice Interface for the PhiEth token contract
* @dev Defines the complete PhiEth token interface including events and errors
*/
interface IPhiEth is IERC20 {
// ============ Events ============
/**
* @notice Emitted when rewards are claimed and distributed
* @param rewardToken Address of the reward token
* @param amount Amount of reward tokens claimed
* @param recipient Address that received the rewards
*/
event RewardsClaimed(address indexed rewardToken, uint256 amount, address indexed recipient);
/**
* @notice Emitted when yield is harvested and distributed
* @param protocolFee Amount sent to protocol fee recipient
* @param yieldAmount Amount sent to yield receiver
*/
event YieldHarvested(uint256 protocolFee, uint256 yieldAmount);
/**
* @notice Emitted when rebalance threshold is updated
* @param oldThreshold Previous threshold value
* @param newThreshold New threshold value
*/
event RebalanceThresholdUpdated(uint256 oldThreshold, uint256 newThreshold);
/**
* @notice Emitted when yield receiver is updated
* @param oldReceiver Previous yield receiver
* @param newReceiver New yield receiver
*/
event YieldReceiverUpdated(address indexed oldReceiver, address indexed newReceiver);
/**
* @notice Emitted when strategy is changed
* @param oldStrategy Previous strategy address
* @param newStrategy New strategy address
*/
event StrategyChanged(address indexed oldStrategy, address indexed newStrategy);
/**
* @notice Emitted when dust amount is ignored during rebalance
*/
event DustAmountIgnored(address indexed strategy, uint256 amount);
// ============ Errors ============
/**
* @notice Thrown when caller is not the creator
*/
error CallerNotCreator();
/**
* @notice Thrown when yield receiver is zero address
*/
error YieldReceiverIsZero();
/**
* @notice Thrown when rebalance threshold exceeds maximum
*/
error RebalanceThresholdExceedsMax();
/**
* @notice Thrown when current strategy has balance and cannot be changed
*/
error CurrentStrategyHasBalance();
/**
* @notice Thrown when withdrawal amount exceeds available ETH balance
*/
error AmountExceedsETHBalance();
/**
* @notice Thrown when unable to send ETH
*/
error UnableToSendETH();
error StrategyAlreadyInitializedForOtherPhiEth();
error InvalidZeroStrategyAddress();
error StrategyNotWhitelisted();
error CallerNotFactory();
// ============ Core Functions ============
/**
* @notice Deposits ETH and/or WETH and mints PhiEth tokens
* @param wethAmount Amount of WETH to deposit (in addition to msg.value ETH)
*/
function deposit(uint256 wethAmount) external payable;
/**
* @notice Withdraws ETH by burning PhiEth tokens
* @param amount Amount of PhiEth tokens to burn and ETH to withdraw
*/
function withdraw(uint256 amount) external;
/**
* @notice Rebalances the position against the strategy
* @dev Converts excess ETH to LSTs when balance exceeds threshold
*/
function rebalance() external;
/**
* @notice Harvests yield from the strategy and distributes to recipients
*/
function harvest() external;
// ============ View Functions ============
/**
* @notice Calculate the amount of yield accumulated
* @return The yield accumulated in ETH
*/
function yieldAccumulated() external view returns (uint256);
/**
* @notice Get the total underlying ETH balance (contract + strategy)
* @return The total amount of underlying ETH held
*/
function underlyingETHBalance() external view returns (uint256);
/**
* @notice Get the creator address
* @return The creator address
*/
function getCreator() external view returns (address);
/**
* @notice Get the current yield receiver address
* @return The yield receiver address
*/
function yieldReceiver() external view returns (address);
/**
* @notice Get the current rebalance threshold
* @return The rebalance threshold value
*/
function rebalanceThreshold() external view returns (uint256);
/**
* @notice Get the current strategy
* @return The strategy contract address
*/
function strategy() external view returns (IBasePhiEthStrategy);
// ============ Configuration Functions ============
/**
* @notice Update the rebalance threshold (creator only)
* @param rebalanceThreshold_ The new rebalance threshold value
*/
function setRebalanceThreshold(uint256 rebalanceThreshold_) external;
/**
* @notice Update the yield receiver address (creator only)
* @param yieldReceiver_ The new yield receiver address
*/
function setYieldReceiver(address yieldReceiver_) external;
/**
* @notice Change the strategy (creator only)
* @param strategy_ The new strategy contract
*/
function changeStrategy(IBasePhiEthStrategy strategy_) external;
/**
* @notice Transfer PhiEth tokens to recipient
* @param recipient The recipient address
* @param amount The amount to transfer
* @return True if transfer succeeded
*/
function transfer(address recipient, uint256 amount) external returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
interface IReferralEscrow {
error MismatchedTokensAndLimits();
error Unauthorized();
error InvalidBoardToken();
error InvalidAddress();
/// Event emitted when tokens are assigned to a user
event TokensAssigned(PoolId indexed _poolId, address indexed _user, address indexed _token, uint256 _amount);
/// Event emitted when a user claims tokens for a specific token address
event TokensClaimed(address indexed _user, address _recipient, address indexed _token, uint256 _amount);
/// Event emitted when a user has swapped their claimed tokens to ETH
event TokensSwapped(address indexed _user, address indexed _token, uint256 _tokenIn, uint256 _ethOut);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { IFeeDistributor } from "./IFeeDistributor.sol";
import { IPhiEthDeployer } from "./IPhiEthDeployer.sol";
/**
* @title IPhiEthFactory
* @dev Interface for PhiEthFactory with all shared structs and errors
*/
interface IPhiEthFactory {
// ---------- All Custom Errors ----------
// General errors
error ZeroAddress();
error ZeroReceiverAddress();
error ZeroImplementationAddress();
error ZeroAddressInParams();
// Access control errors
error OnlyFactory();
error OnlyDeployer();
// Deployment errors
error PhiCloneFailed();
error StrategyDeployFailed();
error StrategyCloneFailed();
error StrategyInitFailed();
error PhiTokenInitFailed();
error PhiETHHookDeployFailed();
error PhiEthTokenNotFound();
error OnlyPhiEthToken();
error ZapDeployFailed();
error FactoryMappingUpdateFailed();
error CreatorMismatch();
error DeployerFactoryNotSet();
error StrategyDeployerNotSet();
error StrategyDeployerMismatch();
// State errors
error FactoryAlreadySet();
error DeployerNotSet();
error FeeManagerNotSet();
// Fee-related errors
error SwapFeeInvalid();
error ReferrerFeeInvalid();
error ProtocolFeeInvalid();
error ProtocolFeeRatioExceedsMax();
// Validation errors
error InvalidAmount();
error InsufficientBalance(uint256 requested, uint256 available);
error InvalidFeeRatio(uint256 provided, uint256 maximum);
error PoolSwapNotProvided();
error BoardManagerNotProvided();
// New dust threshold errors
error DustThresholdTooHigh();
error DustThresholdTooLow();
// ---------- Structs ----------
/**
* @dev Information about a deployed PhiEth token
*/
struct PhiTokenInfo {
address creator;
address strategy;
address phiEthHook;
}
/**
* @dev Parameters for board hook configuration (matching original)
*/
struct BoardHookParams {
address initialPrice;
address feeExemptions;
}
/**
* @dev Parameters for PhiEth deployment (matching original structure)
*/
struct PhiEthDeploymentParams {
string name;
string symbol;
address creator;
address yieldReceiver;
uint8 strategyType;
}
// ---------- Events ----------
event PhiEthCreated(
address indexed phiEthToken, address indexed strategy, address indexed phiEthHook, address creator
);
event ProtocolFeeRecipientUpdated(address indexed protocolFeeRecipient);
event FeeCalculatorUpdated(address indexed feeCalculator);
event FairLaunchFeeCalculatorUpdated(address indexed feeCalculator);
event FeeDistributionUpdated(IFeeDistributor.FeeDistribution feeDistribution);
event ProtocolStrategyFeeRatioUpdated(uint24 indexed protocolStrategyFeeRatio);
event PoolSwapZapUpdated(address indexed poolSwapZap);
event DistributorUpdated(address indexed distributor);
event BoardManagerUpdated(address indexed boardManager);
event MuseManagerUpdated(address indexed museManager);
event ReferralEscrowUpdated(address indexed referralEscrow);
event PremineZapUpdated(address indexed premineZap);
event StrategyDeployerUpdated(address indexed strategyDeployer);
event StrategyWhitelisted(address indexed strategy);
event StrategyUpdated(address indexed phiEthToken, address indexed newStrategy);
event PhiEthProtocolFeeRatioUpdated(address indexed phiEthToken, uint24 feeRatio);
event PhiEthTokenWhitelisted(address indexed phiEthToken, bool whitelisted);
event DustThresholdUpdated(uint256 newDustThreshold);
event StrategyRemovedFromWhitelist(address indexed strategy);
event PhiEthDeployerUpdated(address indexed oldDeployer, address indexed newDeployer);
// ---------- Core Functions ----------
function deployer() external view returns (IPhiEthDeployer);
/**
* @dev Creates a new PhiEth token and its associated components
*/
function createPhiEth(PhiEthDeploymentParams memory params)
external
returns (address phiEthToken, address strategy, address phiEthHook);
function updateStrategyMapping(address phiEthToken, address newStrategy) external;
function addPhiEthTokenToWhitelist(address phiEthToken) external;
// ---------- View Functions ----------
function getUserTokens(address user) external view returns (address[] memory);
function getPhiTokenInfo(address phiEthToken) external view returns (PhiTokenInfo memory);
function isPhiEth(address phiEthToken) external view returns (bool);
function isPhiEthTokenWhitelisted(address phiEthToken) external view returns (bool);
function isStrategyWhitelisted(address strategy) external view returns (bool);
function getPhiEthProtocolFeeRatio(address phiEthToken) external view returns (uint24);
function protocolFeeRecipient() external view returns (address);
function dustThreshold() external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { IBoardHook } from "./IBoardHook.sol";
/**
* Interface for the BoardManager contract that handles token creation
*/
interface IBoardManager {
error CallerIsNotBoardHook();
error CreatorFeeAllocationInvalid(uint24 _allocation, uint256 _maxAllocation);
error InvalidPhiSchedule();
error InvalidInitialSupply(uint256 _initialSupply);
error PremineExceedsInitialAmount(uint256 _buyAmount, uint256 _initialSupply);
error UnknownBoardToken();
error ZeroAddress();
error HookNotRegistered();
error InvalidBoardCreator();
error NotVerifiedBoard(address _creator);
error BoardAlreadyExists(string _attestedId);
error InvalidAddress();
error CallerIsNotBoard();
error CallerIsNotRegisteredBoard();
/// Events
event BoardImplementationUpdated(address indexed oldImplementation, address indexed newImplementation);
event RouterAdded(address indexed router);
event RouterRemoved(address indexed router);
event BoardCreated(
uint256 indexed counter,
address indexed board,
string indexed attestBoardId,
address creator,
address inspirer,
uint256 initialTokenFairLaunch,
uint256 premineAmount,
uint256 publiphiAt
);
event BoardTransfer(
address indexed from,
address indexed to,
address indexed board,
uint256 amount,
uint256 senderBalance,
uint256 receiverBalance
);
/**
* Creates a new token and returns its address along with the treasury address and token ID.
*
* @param _params Parameters for the token creation
* @return boardToken_ The address of the created token
* @return counter_ The ID of the token
*/
function publiphi(IBoardHook.PubliphiParams calldata _params)
external
returns (address boardToken_, uint256 counter_);
function isTrustedRouter(address _router) external view returns (bool);
function creator(address _board) external view returns (address);
function boardToPhiEth(address _board) external view returns (address phiEthToken);
function emitBoardTransfer(address _from, address _to, uint256 _amount) external;
}// 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;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @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) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @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) SafeCastOverflow.selector.revertWith();
}
/// @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) SafeCastOverflow.selector.revertWith();
}
/// @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) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the 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);
}// 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 To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @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);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @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))
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, 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 key The key for the pool being initialized
/// @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, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
using LPFeeLibrary for uint24;
using CustomRevert for bytes4;
/// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
error LPFeeTooLarge(uint24 fee);
/// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
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 mask to remove the override fee flag from a fee returned by the beforeSwaphook
uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;
/// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
uint24 public constant MAX_LP_FEE = 1000000;
/// @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 isDynamicFee(uint24 self) internal pure returns (bool) {
return self == DYNAMIC_FEE_FLAG;
}
/// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
/// @param self The fee to check
/// @return bool True of the fee is valid
function isValid(uint24 self) internal pure returns (bool) {
return self <= MAX_LP_FEE;
}
/// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
/// @param self The fee to validate
function validate(uint24 self) internal pure {
if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
}
/// @notice gets and validates 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 fee (if valid)
function getInitialLPFee(uint24 self) internal pure returns (uint24) {
// the initial fee for a dynamic fee pool is 0
if (self.isDynamicFee()) return 0;
self.validate();
return 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 & REMOVE_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
/// @return fee The fee without the override flag set (if valid)
function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
fee = self.removeOverrideFlag();
fee.validate();
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
// equivalent: (selector,) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
selector := mload(add(result, 0x20))
}
}
function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
// equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
assembly ("memory-safe") {
lpFee := mload(add(result, 0x60))
}
}
function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
// equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
hookReturn := mload(add(result, 0x40))
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
/// @notice Thrown when protocol fee is set too high
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
error InvalidCaller();
/// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
error ProtocolFeeCurrencySynced();
/// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Emitted when the protocol fee is updated for a pool.
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @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 currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Sets the protocol fee for the given pool
/// @param key The key of the pool to set a protocol fee for
/// @param newProtocolFee The fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Sets the protocol fee controller
/// @param controller The new protocol fee controller
function setProtocolFeeController(address controller) external;
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the current protocol fee controller address
/// @return address The current protocol fee controller address
function protocolFeeController() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
/**
* @title IBasePhiEthStrategy
* @notice Interface for all PhiEth strategies with events and errors
* @dev Defines the complete contract interface including events and custom errors
*/
interface IBasePhiEthStrategy {
// ============ Events ============
/**
* @notice Emitted when a strategy is initialized
* @param phiEth Address of the PhiEth token
*/
event StrategyInitialized(address indexed phiEth);
/**
* @notice Emitted when unwinding status changes
* @param isUnwinding New unwinding status
*/
event UnwindingStatusChanged(bool isUnwinding);
/**
* @notice Emitted when ETH is deposited into the strategy
* @param ethAmount Amount of ETH deposited
* @param sharesReceived Amount of strategy tokens received
*/
event ETHDeposited(uint256 ethAmount, uint256 sharesReceived);
/**
* @notice Emitted when ETH is withdrawn from the strategy
* @param sharesRedeemed Amount of strategy tokens redeemed
* @param ethReceived Amount of ETH received
* @param recipient Address that received the ETH
*/
event ETHWithdrawn(uint256 sharesRedeemed, uint256 ethReceived, address indexed recipient);
// ============ Errors ============
/**
* @notice Thrown when caller is not the PhiEth token contract
*/
error CallerIsNotPhiEth();
/**
* @notice Thrown when caller is not the PhiEth owner
*/
error CallerIsNotPhiEthOwner();
/**
* @notice Thrown when strategy is already initialized
*/
error AlreadyInitialized();
/**
* @notice Thrown when strategy is not initialized
*/
error NotInitialized();
/**
* @notice Thrown when PhiEth address is invalid (zero address)
*/
error InvalidPhiEthAddress();
/**
* @notice Thrown when amount must be greater than zero
*/
error AmountMustBeGreaterThanZero();
/**
* @notice Thrown when recipient address is invalid (zero address)
*/
error InvalidRecipientAddress();
/**
* @notice Thrown when there is insufficient balance for operation
*/
error InsufficientBalance();
/**
* @notice Thrown when token address is invalid
*/
error InvalidTokenAddress();
/**
* @notice Thrown when ETH transfer fails
*/
error ETHTransferFailed();
/**
* @notice Thrown when token transfer fails
*/
error TokenTransferFailed();
// ============ Core Strategy Functions ============
function initialize(address phiEth) external;
/**
* @notice Deposits incoming ETH into the underlying protocol and mints LST
* @dev The LST tokens remain in this contract to earn yield
*/
function convertETHToLST() external payable;
/**
* @notice Withdraws ETH from the strategy and sends it to the recipient
* @param amount Amount of ETH to withdraw
* @param recipient Address to receive the ETH
*/
function withdrawETH(uint256 amount, address recipient) external;
/**
* @notice Returns the total ETH balance represented by the strategy's holdings
* @return The balance in ETH terms
*/
function balanceInETH() external view returns (uint256);
// ============ Administrative Functions ============
/**
* @notice Sets whether the strategy is currently unwinding
* @param isUnwinding_ New unwinding status
*/
function setIsUnwinding(bool isUnwinding_) external;
/**
* @notice Allows the owner to unwind the strategy in small amounts into ETH
* @param ethAmount Amount of ETH to unwind to
*/
function unwindToETH(uint256 ethAmount) external;
// ============ View Functions ============
/**
* @notice Returns the address of the PhiEth token
* @return The PhiEth token address
*/
function phiEth() external view returns (address);
/**
* @notice Returns whether the strategy is currently unwinding
* @return True if strategy is unwinding
*/
function isUnwinding() external view returns (bool);
function isInitialized() external view returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
import { IFeeCalculator } from "./IFeeCalculator.sol";
interface IFeeDistributor {
error InvalidZeroAddress();
error SwapFeeInvalid();
error ReferrerFeeInvalid();
error ProtocolFeeInvalid();
/**
* Stores the percentages of fee distribution.
*
* @dev This works in a waterfall approach, with a percentage taking a share before
* passing the potential allocation on to the next. This means that the percentages
* listed don't need to equal 100%:
*
* `Fee priority: baseSwapFee swapfee -> referrer -> protocol -> creator `
*
* @member baseSwapFee The amount of the transaction taken as fee
* @member referrer The percentage that the referrer will receive
* @member swapper The percentage that the swapper will receive
* @member protocol The percentage that the protocol will receive
* @member active If a FeeDistribution struct has been set for the mapping
*/
struct FeeDistribution {
uint24 baseSwapFee;
uint24 referrer;
uint24 swapper;
uint24 protocol;
uint24 inspirer;
bool active;
}
event FeeCalculatorUpdated(address indexed feeCalculator);
event FairLaunchFeeCalculatorUpdated(address indexed feeCalculator);
event FeeDistributionUpdated(FeeDistribution _feeDistribution);
/// Emitted when fees are added to a payee
event Deposit(PoolId indexed _poolId, address _payee, address _token, uint256 _amount, string _reason);
/// Emitted when fees are withdrawn to a payee
event Withdrawal(address _sender, address _recipient, address _token, uint256 _amount, bool _unwrap);
/// Emitted when a referrer fee has been paid out
event ReferrerFeePaid(PoolId indexed _poolId, address _recipient, address _token, uint256 _amount);
/**
* @notice Gets the appropriate fee calculator based on launch status
* @param _isFairLaunch If the pool is currently in FairLaunch
* @return The IFeeCalculator to use
*/
function getFeeCalculator(bool _isFairLaunch) external view returns (IFeeCalculator);
/**
* @notice Gets the fee distribution for a specific pool
* @param _poolId The pool ID to get fee distribution for
* @return feeDistribution_ The fee distribution configuration
*/
function getPoolFeeDistribution(PoolId _poolId) external view returns (FeeDistribution memory);
function poolPhiEthToken(PoolId _poolId) external view returns (address phiEthToken);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { IPhiEthFactory } from "./IPhiEthFactory.sol";
import { IStrategyDeployer } from "./IStrategyDeployer.sol";
/**
* @title IPhiEthDeployer
* @dev Interface for PhiEthDeployer contract - events come from IPhiEthFactory
*/
interface IPhiEthDeployer {
// ---------- Events ----------
event PhiEthDeployed(
address indexed phiEthToken, address indexed strategy, address indexed creator, string name, string symbol
);
event HooksDeployed(address indexed phiEthToken, address indexed phiEthHook);
// ---------- Custom Errors ----------
error ZeroReceiverAddress();
error PhiCloneFailed();
error StrategyDeployFailed();
error PhiTokenInitFailed();
error PhiETHHookDeployFailed();
error OnlyFactory();
error FactoryAlreadySet();
error FactoryMappingUpdateFailed();
error InvalidSalt();
// ---------- Functions ----------
/**
* @dev Sets the factory address (called after factory deployment)
*/
function setFactory(address _factory) external;
function setStrategyDeployer(address _strategyDeployer) external;
/**
* @dev Deploys a complete PhiEth ecosystem using pre-calculated salts
*/
function deployPhiEth(
IPhiEthFactory.PhiEthDeploymentParams memory params,
bytes32 phiEthHookSalt
)
external
returns (address phiEthToken, address strategy, address phiEthHook);
function factory() external returns (address);
function strategyDeployer() external returns (IStrategyDeployer);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { FeeExemptions } from "../fee/FeeExemptions.sol";
import { FairLaunch } from "../board/FairLaunch.sol";
import { Notifier } from "../libraries/Notifier.sol";
import { IPoolManager } from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import { IInitialPrice } from "../interfaces/IInitialPrice.sol";
import { IBoardManager } from "../interfaces/IBoardManager.sol";
import { IMuseManager } from "../interfaces/IMuseManager.sol";
import { IFeeExemptions } from "../interfaces/IFeeExemptions.sol";
import { IFeeDistributor } from "../interfaces/IFeeDistributor.sol";
import { IFeeCalculator } from "../interfaces/IFeeCalculator.sol";
/**
* Interface for the BoardHook contract that controls the user journey from token creation,
* to fair launch, to ongoing swaps.
*/
interface IBoardHook {
/**
* Errors
*/
// ========== Errors ==========
error PhiEthTokenNotWhitelisted(address token);
error CannotBeInitializedDirectly();
error InsufficientPubliphiFee(uint256 _required);
error TokenNotPubliphied(uint256 _publiphiesAt);
error NotFairLaunchWhitelisted(address initiater, address _sender);
error Unauthorized();
/**
* Events
*/
/// Emitted when a Publiphi pool is created
event PoolCreated(
PoolId indexed _poolId,
address _boardToken,
uint256 _counter,
bool _currencyFlipped,
uint256 _publiphiFee,
PubliphiParams _params,
uint256 _actualPubliphiAt
);
/// Emitted when a pool swap occurs
event PoolSwap(
PoolId indexed poolId,
address indexed sender,
address indexed initiater,
int256 pubiliphiAmount0,
int256 pubiliphiAmount1,
int256 pubiliphiFee0,
int256 pubiliphiFee1,
int256 uniAmount0,
int256 uniAmount1,
int256 uniFee0,
int256 uniFee1,
bool isBuy
);
event HookSwap(
bytes32 indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint128 hookLPfeeAmount0,
uint128 hookLPfeeAmount1
);
event HookModifyLiquidity(bytes32 indexed id, address indexed sender, int128 amount0, int128 amount1);
/// Emitted after any transaction to share pool state
event PoolStateUpdated(
PoolId indexed _poolId,
uint160 _sqrtPriceX96,
int24 _tick,
uint24 _protocolFee,
uint24 _swapFee,
uint128 _liquidity
);
/// Emitted when a user successfully premines their token
event PoolPremine(PoolId indexed _poolId, int256 _premineAmount);
event FairLaunchBurn(PoolId indexed _poolId, uint256 _unsoldSupply);
/**
* Structs
*/
/**
* If the creator requests a premine amount of tokens, then these will be cast
* to this structure.
*
* @member amountSpecified The amount of tokens requested to buy as creator
* @member blockNumber The block that the premine is created and allocated
*/
struct PoolPremineInfo {
int256 amountSpecified;
uint256 blockNumber;
}
struct SwapData {
address referrer;
bytes32[] proof;
uint256 maxAllocation;
}
/**
* Defines our constructor parameters.
*
* @member boardManager The {BoardManager} contract
* @member museManager The {MuseManager} contract
* @member poolManager The Uniswap V4 {PoolManager} contract
* @member initialPrice Set initial price calculator address
* @member protocolOwner The EOA that will be the initial owner
* @member protocolFeeRecipient The recipient EOA of all
* @member feeExemptions The default global FeeExemption values
* @member phiEthFactory The {PhiEthFactory} contract
*/
struct ConstructorParams {
IBoardManager boardManager;
IMuseManager museManager;
IPoolManager poolManager;
IInitialPrice initialPrice;
address protocolOwner;
address protocolFeeRecipient;
IFeeExemptions feeExemptions;
address phiEthFactory;
IFeeDistributor.FeeDistribution feeDistribution;
}
/**
* Parameters required when publiphiing a new token.
*
* @member attestBoardId The ID of the board
* @member initialTokenFairLaunch The amount of tokens to add as single sided fair launch liquidity
* @member premineAmount The amount of tokens that the creator will buy themselves
* @member creator The address of the creator of the token
* @member phiEthToken The address of the PhiEth token to be created
* @member publiphiAt The timestamp at which the token will launch
* @member initialPriceParams The encoded parameters for the Initial Price logic
* @member feeCalculatorParams The encoded parameters for the fee calculator
* @member merkleRoot The merkle root for the airdrop
* @member inspirer The address of the inspirer, if any
*/
struct PubliphiParams {
string attestBoardId;
uint256 initialTokenFairLaunch;
uint256 premineAmount;
address creator;
address phiEthToken;
uint256 publiphiAt;
bytes initialPriceParams;
bytes feeCalculatorParams;
bytes32 merkleRoot;
address inspirer;
string publiphiURL;
}
/**
* External Functions
*/
function publiphi(PubliphiParams calldata _params) external payable returns (address boardToken_);
function poolKey(address _token) external view returns (PoolKey memory);
function getPubliphiFee(bytes calldata _initialPriceParams) external view returns (uint256);
function getPubliphiMarketCap(bytes calldata _initialPriceParams) external view returns (uint256);
function setInitialPrice(address _initialPrice) external;
/**
* Public Variables
*/
function fairLaunch() external view returns (FairLaunch);
function notifier() external view returns (Notifier);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { BalanceDelta } from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import { IPoolManager } from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { SwapParams } from "@uniswap/v4-core/src/types/PoolOperation.sol";
interface IFeeCalculator {
error InvalidAddress();
function determineSwapFee(
PoolKey memory _poolKey,
SwapParams memory _params,
uint24 _baseFee
)
external
view
returns (uint24 swapFee_);
function trackSwap(
address _sender,
PoolKey calldata _poolKey,
SwapParams calldata _params,
BalanceDelta _delta,
bytes calldata _hookData
)
external;
function setPubliphiParams(PoolId _poolId, bytes calldata _params) external;
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { IPhiEthDeployer } from "../interfaces/IPhiEthDeployer.sol";
/**
* @title IStrategyDeployer
* @notice Interface for the StrategyDeployer contract
*/
interface IStrategyDeployer {
// ============ Events ============
event StrategyDeployed(address indexed strategy, address indexed phiEthToken, uint8 strategyType);
event StrategyTypeStatusUpdated(uint8 indexed strategyType, bool isOpen);
// ============ Errors ============
error InvalidPhiEthToken();
error UnsupportedStrategyType();
error StrategyInitializationFailed();
error InvalidImplementation();
error InvalidZeroAddress();
error InvalidCaller();
// ============ External Functions ============
/**
* @notice Deploys a strategy clone based on the specified type
* @param phiEthToken Address of the PhiEth token
* @param strategyType Type of strategy to deploy
* @return strategy Address of the deployed strategy clone
*/
function deployStrategy(address phiEthToken, uint8 strategyType) external returns (address strategy);
/**
* @notice Sets the PhiEthDeployer address
* @param _phiEthDeployer New PhiEthDeployer address
*/
function setPhiEthDeployer(address _phiEthDeployer) external;
function phiEthDeployer() external returns (IPhiEthDeployer);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IFeeExemptions } from "../interfaces/IFeeExemptions.sol";
import { LPFeeLibrary } from "@uniswap/v4-core/src/libraries/LPFeeLibrary.sol";
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
/**
* This contract will allow for specific addresses to have reduced or nullified fees for all
* swaps transactions within the pool. These will be allocated to partners that need a more
* consistent underlying price to ensure their protocol can operate using Publiphi pools.
* @dev Based on: https://github.com/flayerlabs
*/
contract FeeExemptions is Ownable2Step, IFeeExemptions {
using LPFeeLibrary for uint24;
/// Stores a mapping of beneficiaries and that flat fee exemptions
mapping(address _beneficiary => mapping(PoolId _poolId => FeeExemption _exemption)) internal _feeExemption;
/**
* Registers the caller as the contract owner.
*
* @param _protocolOwner The initial EOA owner of the contract
*/
constructor(address _protocolOwner) Ownable(_protocolOwner) { }
/**
* Gets the `FeeExemption` data struct for a beneficiary address.
*
* @param _beneficiary The address of the beneficiary
*
* @return The FeeExemption struct for the beneficiary
*/
function feeExemption(address _beneficiary, PoolId _poolId) public view returns (FeeExemption memory) {
return _feeExemption[_beneficiary][_poolId];
}
/**
* Set our beneficiary's flat fee rate across all pools. If a beneficiary is set, then
* the fee processed during a swap will be overwritten if this fee exemption value is
* lower than the otherwise determined fee.
*
* @param _beneficiary The swap `sender` that will receive the exemption
* @param _flatFee The flat fee value that the `_beneficiary` will receive
*/
function setFeeExemption(address _beneficiary, PoolId _poolId, uint24 _flatFee) public onlyOwner {
if (!_flatFee.isValid()) revert FeeExemptionInvalid(_flatFee, LPFeeLibrary.MAX_LP_FEE);
_feeExemption[_beneficiary][_poolId] = FeeExemption(_flatFee, true);
emit BeneficiaryFeeSet(_beneficiary, _poolId, _flatFee);
}
/**
* Removes a beneficiary fee exemption.
*
* @dev If the `beneficiary` does not already have an exemption, this call will revert.
*
* @param _beneficiary The address to remove the fee exemption from
*/
function removeFeeExemption(address _beneficiary, PoolId _poolId) public onlyOwner {
if (!_feeExemption[_beneficiary][_poolId].enabled) {
revert NoBeneficiaryExemption(_beneficiary, _poolId);
}
delete _feeExemption[_beneficiary][_poolId];
emit BeneficiaryFeeRemoved(_beneficiary, _poolId);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { BeforeSwapDelta, toBeforeSwapDelta } from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import { BalanceDelta, toBalanceDelta } from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import { Currency } from "@uniswap/v4-core/src/types/Currency.sol";
import { FullMath } from "@uniswap/v4-core/src/libraries/FullMath.sol";
import { IPoolManager } from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import { LiquidityAmounts } from "@uniswap/v4-core/test/utils/LiquidityAmounts.sol";
import { PoolId, PoolIdLibrary } from "@uniswap/v4-core/src/types/PoolId.sol";
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { SafeCast } from "@uniswap/v4-core/src/libraries/SafeCast.sol";
import { TickMath } from "@uniswap/v4-core/src/libraries/TickMath.sol";
import { MerkleProofLib } from "solady/utils/MerkleProofLib.sol";
import { CurrencySettler } from "../libraries/CurrencySettler.sol";
import { TickFinder } from "../libraries/TickFinder.sol";
import { ModifyLiquidityParams } from "@uniswap/v4-core/src/types/PoolOperation.sol";
import { IFairLaunch } from "../interfaces/IFairLaunch.sol";
/**
* Adds functionality to the {BoardHook} that promotes a fair token launch.
*
* This creates a time window right after the token is launched that keeps the token at
* the same price in a single tick position. Fees earned from this are kept within the
* position and cannot be sold into until the fair launch window has finished.
*
* Once the FairLaunch period has ended, the ETH raised and the remaining tokens are
* both deployed into a Uniswap position to facilitate ongoing transactions and create
* a price discovery.
*
* @dev Based on: https://github.com/fico23/fundraise-hook
* @dev Based on: https://github.com/flayerlabs
*/
contract FairLaunch is IFairLaunch {
using CurrencySettler for Currency;
using PoolIdLibrary for PoolKey;
using SafeCast for *;
using TickFinder for int24;
/// Our fair launch window duration
uint256 public constant FAIR_LAUNCH_WINDOW = 30 minutes;
/// Maps a PoolId to a FairLaunchInfo struct
mapping(PoolId _poolId => FairLaunchInfo _info) internal _fairLaunchInfo;
mapping(PoolId _poolId => address _phiEthToken) public poolPhiEthToken;
mapping(PoolId => mapping(address => uint256)) private _userPurchases;
/// Our Uniswap V4 {PoolManager} contract address
IPoolManager private immutable poolManager;
/// Our Publiphi {BoardHook} address
address private immutable boardHook;
/**
* Stores our native token.
*
* @param _poolManager The Uniswap V4 {PoolManager} contract
*/
constructor(IPoolManager _poolManager) {
poolManager = _poolManager;
// Set our {BoardHook} as the caller
boardHook = msg.sender;
}
/**
* Checks if the {PoolKey} is within the fair launch window.
*
* @param _poolId The ID of the PoolKey
*
* @return If the {PoolKey} is within the fair launch window
*/
function inFairLaunchWindow(PoolId _poolId) external view returns (bool) {
FairLaunchInfo memory info = _fairLaunchInfo[_poolId];
return block.timestamp >= info.startsAt && block.timestamp < info.endsAt;
}
/**
* Helper function to call the FairLaunchInfo struct for a pool.
*
* @param _poolId The ID of the PoolKey
*
* @return The FairLaunchInfo for the pool
*/
function fairLaunchInfo(PoolId _poolId) external view returns (FairLaunchInfo memory) {
return _fairLaunchInfo[_poolId];
}
/**
* Creates an initial fair launch position.
*
* @param _poolId The ID for the pool being initialized
* @param _initialTokenFairLaunch The amount of tokens to add as single sided fair launch liquidity
*/
function createPosition(
PoolId _poolId,
address _phiEthToken,
int24 _initialTick,
uint256 _publiphiesAt,
uint256 _initialTokenFairLaunch
)
public
virtual
onlyBoardHook
returns (FairLaunchInfo memory)
{
if (_initialTokenFairLaunch == 0){
revert InvalidLaunchParameters();
}
poolPhiEthToken[_poolId] = _phiEthToken;
// Determine the time that the fair launch window will close
uint256 endsAt = _publiphiesAt + FAIR_LAUNCH_WINDOW;
// Map these tokens into an pseudo-escrow that we can reference during the sale
// and activate our pool fair launch window.
_fairLaunchInfo[_poolId] = IFairLaunch.FairLaunchInfo({
startsAt: _publiphiesAt,
endsAt: endsAt,
initialTick: _initialTick,
revenue: 0,
supply: _initialTokenFairLaunch,
closed: false,
phiEthToken: _phiEthToken,
initialTokenFairLaunch: _initialTokenFairLaunch
});
emit FairLaunchCreated(_poolId, _initialTokenFairLaunch, _publiphiesAt, endsAt);
}
/**
* Closes the FairLaunch position and recreates the position as a wide range position immediately
* above the tick for our boardToken. This position is comprised of any unsold Memecoin
* from the FairLaunch, as well as the remaining supply from mint.
*
* @param _poolKey The PoolKey we are closing the FairLaunch position of
* @param _tokenFees The amount of token fees that need to remain in the {BoardHook}
* @param _nativeIsZero If our native token is `currency0`
*/
function closePosition(
PoolKey memory _poolKey,
uint256 _tokenFees,
bool _nativeIsZero
)
external
onlyBoardHook
returns (FairLaunchInfo memory)
{
// Reference the pool's FairLaunchInfo, ready to store updated values
FairLaunchInfo storage info = _fairLaunchInfo[_poolKey.toId()];
int24 tickLower;
int24 tickUpper;
if (_nativeIsZero) {
// ETH position
tickLower = (info.initialTick + 1).validTick(false);
tickUpper = tickLower + TickFinder.TICK_SPACING;
_createImmutablePosition(_poolKey, tickLower, tickUpper, info.revenue, true);
// boardToken position
tickLower = TickFinder.MIN_TICK;
tickUpper = (info.initialTick - 1).validTick(true);
_createImmutablePosition(
_poolKey,
tickLower,
tickUpper,
_poolKey.currency1.balanceOf(address(boardHook)) - _tokenFees - info.supply,
false
);
} else {
// ETH position
tickUpper = (info.initialTick - 1).validTick(true);
tickLower = tickUpper - TickFinder.TICK_SPACING;
_createImmutablePosition(_poolKey, tickLower, tickUpper, info.revenue, false);
// boardToken position
tickLower = (info.initialTick + 1).validTick(false);
tickUpper = TickFinder.MAX_TICK;
_createImmutablePosition(
_poolKey,
tickLower,
tickUpper,
_poolKey.currency0.balanceOf(address(boardHook)) - _tokenFees - info.supply,
true
);
}
uint256 originalEndsAt = info.endsAt;
uint256 actualEndsAt = block.timestamp < originalEndsAt ? block.timestamp : originalEndsAt;
info.endsAt = actualEndsAt;
info.closed = true;
// Emit our FairLaunchEnded event
emit FairLaunchEnded(_poolKey.toId(), info.revenue, info.supply, info.endsAt);
return info;
}
/**
* When we are filling from our Fair Launch position, we will always be buying tokens
* with ETH. The amount specified that is passed in, however, could be positive or negative.
*
* The positive / negative flag will require us to calculate the amount the user will get in
* a different way. Positive: How much ETH it costs to get amount. Negative: How many tokens
* I can get for amount.
*
* The amount requested **can** exceed the Fair Launch position, but we will additionally
* have to call `_closeFairLaunchPosition` to facilitate it during this call. This will
* provide additional liquidity before the swap actually takes place.
*
* @dev `zeroForOne` will always be equal to `_nativeIsZero` as it will always be ETH -> Token.
*
* @param _poolKey The PoolKey we are filling from
* @param _amountSpecified The amount specified in the swap
* @param _nativeIsZero If our native token is `currency0`
*
* @return beforeSwapDelta_ The modified swap delta
*/
function fillFromPosition(
PoolKey memory _poolKey,
int256 _amountSpecified,
bool _nativeIsZero,
address _sender,
uint256 _maxAllocation
)
external
onlyBoardHook
returns (BeforeSwapDelta beforeSwapDelta_, BalanceDelta balanceDelta_, FairLaunchInfo memory fairLaunchInfo_)
{
PoolId poolId = _poolKey.toId();
FairLaunchInfo storage info = _fairLaunchInfo[poolId];
if (_amountSpecified == 0) {
return (beforeSwapDelta_, balanceDelta_, info);
}
uint256 ethIn;
uint256 tokensOut;
// If we have a negative amount specified, then we have an ETH amount passed in and want
// to buy as many tokens as we can for that price.
if (_amountSpecified < 0) {
ethIn = uint256(-_amountSpecified);
tokensOut = _getQuoteAtTick(
info.initialTick,
ethIn,
Currency.unwrap(_nativeIsZero ? _poolKey.currency0 : _poolKey.currency1),
Currency.unwrap(_nativeIsZero ? _poolKey.currency1 : _poolKey.currency0)
);
}
// Otherwise, if we have a positive amount specified, then we know the number of tokens that
// are being purchased and need to calculate the amount of ETH required.
else {
tokensOut = uint256(_amountSpecified);
ethIn = _getQuoteAtTick(
info.initialTick,
tokensOut,
Currency.unwrap(!_nativeIsZero ? _poolKey.currency0 : _poolKey.currency1),
Currency.unwrap(!_nativeIsZero ? _poolKey.currency1 : _poolKey.currency0)
);
}
// in case of 0 allocation, no need to proceed
if (_maxAllocation > 0) {
// check tokensOut against the max allocation
if (tokensOut > _maxAllocation - _userPurchases[poolId][_sender]) {
// error if the requested amount exceeds the max allocation
revert IFairLaunch.ExceedsMaxAllocation(
_sender, tokensOut, _maxAllocation, _userPurchases[poolId][_sender]
);
}
// update the user purchases
_userPurchases[poolId][_sender] += tokensOut;
}
// If the user has requested more tokens than are available in the fair launch, then we
// need to strip back the amount that we can fulfill.
if (tokensOut > info.supply) {
// Use FullMath for precise calculation without percentage
// This avoids the rounding-to-zero issue
ethIn = FullMath.mulDiv(ethIn, info.supply, tokensOut);
// Ensure minimum payment to prevent free tokens
if (ethIn == 0 && info.supply > 0) {
ethIn = 1; // Minimum 1 wei
}
// Update our `tokensOut` to the supply limit
tokensOut = info.supply;
}
// Get our BeforeSwapDelta response ready
beforeSwapDelta_ = (_amountSpecified < 0)
? toBeforeSwapDelta(ethIn.toInt128(), -tokensOut.toInt128())
: toBeforeSwapDelta(-tokensOut.toInt128(), ethIn.toInt128());
// Define our BalanceDelta
balanceDelta_ = toBalanceDelta(
_nativeIsZero ? ethIn.toInt128() : -tokensOut.toInt128(),
_nativeIsZero ? -tokensOut.toInt128() : ethIn.toInt128()
);
info.revenue += ethIn;
info.supply -= tokensOut;
return (beforeSwapDelta_, balanceDelta_, info);
}
/**
* Allows calls from the {BoardHook} to modify the amount of revenue stored against a pool's
* FairLaunch position. This is required to correctly attribute fees taken.
*
* @param _poolId The ID of the PoolKey
* @param _revenue The revenue amount to add or subtract
*/
function modifyRevenue(PoolId _poolId, int256 _revenue) external onlyBoardHook {
if (_revenue < 0) {
_fairLaunchInfo[_poolId].revenue -= uint256(-_revenue);
} else if (_revenue > 0) {
_fairLaunchInfo[_poolId].revenue += uint256(_revenue);
}
}
function isWhitelisted(
address _sender,
bytes32 _merkleRoot,
bytes32[] calldata _proof,
uint256 _maxAllocation
)
external
pure
returns (bool)
{
bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(_sender, _maxAllocation))));
return MerkleProofLib.verifyCalldata(_proof, _merkleRoot, leaf);
}
/**
* Creates an immutable, single-sided position when the FairLaunch window is closed.
*
* @param _poolKey The PoolKey to create a position against
* @param _tickLower The lower tick of the position
* @param _tickUpper The upper tick of the position
* @param _tokens The number of tokens to put into the position
* @param _tokenIsZero True if the position is created `currency0`; false is `currency1`
*/
function _createImmutablePosition(
PoolKey memory _poolKey,
int24 _tickLower,
int24 _tickUpper,
uint256 _tokens,
bool _tokenIsZero
)
internal
{
// Calculate the liquidity delta based on the tick range and token amount
uint128 liquidityDelta = _tokenIsZero
? LiquidityAmounts.getLiquidityForAmount0({
sqrtPriceAX96: TickMath.getSqrtPriceAtTick(_tickLower),
sqrtPriceBX96: TickMath.getSqrtPriceAtTick(_tickUpper),
amount0: _tokens
})
: LiquidityAmounts.getLiquidityForAmount1({
sqrtPriceAX96: TickMath.getSqrtPriceAtTick(_tickLower),
sqrtPriceBX96: TickMath.getSqrtPriceAtTick(_tickUpper),
amount1: _tokens
});
// If we have no liquidity, then exit before creating the position which would revert
if (liquidityDelta == 0) return;
// Create our single-sided position
(BalanceDelta delta,) = poolManager.modifyLiquidity({
key: _poolKey,
params: ModifyLiquidityParams({
tickLower: _tickLower,
tickUpper: _tickUpper,
liquidityDelta: liquidityDelta.toInt128(),
salt: ""
}),
hookData: ""
});
// Settle the tokens that are required to fill the position
if (delta.amount0() < 0) {
_poolKey.currency0.settle(poolManager, address(boardHook), uint256(-int256(delta.amount0())), false);
}
if (delta.amount1() < 0) {
_poolKey.currency1.settle(poolManager, address(boardHook), uint256(-int256(delta.amount1())), false);
}
}
/**
* Given a tick and a token amount, calculates the amount of token received in exchange.
*
* @dev Forked from the `Uniswap/v3-periphery` {OracleLibrary} contract.
*
* @param _tick Tick value used to calculate the quote
* @param _baseAmount Amount of token to be converted
* @param _baseToken Address of an ERC20 token contract used as the baseAmount denomination
* @param _quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
*
* @return quoteAmount_ Amount of quoteToken received for baseAmount of baseToken
*/
function _getQuoteAtTick(
int24 _tick,
uint256 _baseAmount,
address _baseToken,
address _quoteToken
)
internal
pure
returns (uint256 quoteAmount_)
{
uint160 sqrtPriceX96 = TickMath.getSqrtPriceAtTick(_tick);
// Calculate `quoteAmount` with better precision if it doesn't overflow when multiplied
// by itself.
if (sqrtPriceX96 <= type(uint128).max) {
uint256 ratioX192 = uint256(sqrtPriceX96) * sqrtPriceX96;
quoteAmount_ = _baseToken < _quoteToken
? FullMath.mulDiv(ratioX192, _baseAmount, 1 << 192)
: FullMath.mulDiv(1 << 192, _baseAmount, ratioX192);
} else {
uint256 ratioX128 = FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, 1 << 64);
quoteAmount_ = _baseToken < _quoteToken
? FullMath.mulDiv(ratioX128, _baseAmount, 1 << 128)
: FullMath.mulDiv(1 << 128, _baseAmount, ratioX128);
}
}
/**
* Ensures that only the immutable {BoardHook} can call the function.
*/
modifier onlyBoardHook() {
if (msg.sender != boardHook) revert NotBoardHook();
_;
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
import { ISubscriber } from "../interfaces/ISubscriber.sol";
/**
* Notifier is used to opt in to sending updates to external contracts about position modifications
* against a managed pool.
*/
contract Notifier is Ownable2Step {
using EnumerableSet for EnumerableSet.AddressSet;
error SubscriptionReverted();
event Subscription(address _subscriber);
event Unsubscription(address _subscriber);
/// Store a list of subscribed contracts
EnumerableSet.AddressSet internal subscribers;
/// Store the {BoardHook} that created this contract
address internal _boardHook;
/**
* Registers the caller as the contract owner.
*
* @param _protocolOwner The initial EOA owner of the contract
*/
constructor(address _protocolOwner) Ownable(_protocolOwner) {
_boardHook = msg.sender;
}
/**
* Subscribes a contract to receive updates regarding pool modifications.
*
* @param _subscriber The address of the contract being subscribed
* @param _data Any data passed to subscription call
*/
function subscribe(address _subscriber, bytes calldata _data) public onlyOwner {
// Add the subscriber to our array, which returns true if address is not already
// present in our EnumerableSet.
if (subscribers.add(_subscriber)) {
// Check if we receive a success response. If not, we cannot subscribe the address
if (!ISubscriber(_subscriber).subscribe(_data)) {
revert SubscriptionReverted();
}
emit Subscription(_subscriber);
}
}
/**
* Removes a subscriber based on the index they were stored at.
*
* @param _subscriber The address of the subscriber to unsubscribe
*/
function unsubscribe(address _subscriber) public onlyOwner {
// If we have referenced an empty index, prevent futher processing
if (!subscribers.contains(_subscriber)) {
return;
}
// Delete our subscriber by the index
subscribers.remove(_subscriber);
// Unsubscribe our subscriber, catching the revert in case the contract has become corrupted
try ISubscriber(_subscriber).unsubscribe() { } catch { }
emit Unsubscription(_subscriber);
}
/**
* Send our pool modification notification to all subscribers.
*
* @param _poolId The PoolId that was modified
*/
function notifySubscribers(PoolId _poolId, bytes4 _key, bytes calldata _data) public {
// Ensure that the {BoardHook} sent this notification
require(msg.sender == _boardHook);
// Iterate over all subscribers to pass on data
uint256 subscribersLength = subscribers.length();
for (uint256 i; i < subscribersLength; ++i) {
ISubscriber(subscribers.at(i)).notify(_poolId, _key, _data);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
interface IInitialPrice {
event InitialSqrtPriceX96Updated(uint160 _unflipped, uint160 _flipped);
event PubliphiFeeUpdated(uint256 _publiphiFee);
function getPubliphiFee(address _sender, bytes calldata _initialPriceParams) external view returns (uint256);
function getMarketCap(bytes calldata _initialPriceParams) external view returns (uint256);
function getSqrtPriceX96(
address _sender,
bool _flipped,
bytes calldata _initialPriceParams
)
external
view
returns (uint160);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
/**
* @title IMuseManager
* @dev Interface for managing inspiration relationships and tracking top contributors for board tokens
*/
interface IMuseManager {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/**
* @dev Emitted when inspiration threshold is updated
* @param oldThreshold Previous threshold value
* @param newThreshold New threshold value
* @param timestamp Block timestamp when update occurred
*/
event InspirationThresholdUpdated(uint256 oldThreshold, uint256 newThreshold, uint256 timestamp);
/**
* @dev Emitted when epoch is incremented
* @param newEpoch New epoch number
* @param timestamp Block timestamp when increment occurred
*/
event EpochIncremented(uint256 newEpoch, uint256 timestamp);
/**
* @dev Emitted when a board is registered
* @param boardAddress Address of the board token
* @param creator Address of the board creator
* @param timestamp Block timestamp when registration occurred
*/
event BoardRegistered(address indexed boardAddress, address indexed creator, uint256 timestamp);
/**
* @dev Emitted when an inspirer is registered for a board
* @param boardAddress Address of the board token
* @param creator Address of the board creator
* @param inspirer Address of the designated inspirer
* @param timestamp Block timestamp when registration occurred
*/
event InspirerRegistered(
address indexed boardAddress, address indexed creator, address indexed inspirer, uint256 timestamp
);
/**
* @dev Emitted when an inspirer is updated for a board
* @param boardAddress Address of the board token
* @param oldInspirer Previous inspirer address
* @param newInspirer New inspirer address
* @param timestamp Block timestamp when update occurred
*/
event InspirerUpdated(
address indexed boardAddress, address indexed oldInspirer, address indexed newInspirer, uint256 timestamp
);
/**
* @dev Emitted when active wallet minimum balance is updated
* @param oldMinBalance Previous minimum balance
* @param newMinBalance New minimum balance
* @param timestamp Block timestamp when update occurred
*/
event ActiveWalletMinBalanceUpdated(uint256 oldMinBalance, uint256 newMinBalance, uint256 timestamp);
/**
* @dev Emitted when top contributor is updated for a board
* @param boardAddress Address of the board token
* @param oldTopContributor Previous top contributor address
* @param newTopContributor New top contributor address
* @param inspirationCount Number of unique inspirations
* @param epoch Epoch when update occurred
* @param timestamp Block timestamp when update occurred
*/
event TopContributorUpdated(
address indexed boardAddress,
address indexed oldTopContributor,
address indexed newTopContributor,
uint256 inspirationCount,
uint256 epoch,
uint256 timestamp
);
/**
* @dev Emitted when top contributors list is updated
* @param boardAddress Address of the board token
* @param contributor Address of the contributor
* @param inspirationCount Number of unique inspirations
* @param rank Rank in top contributors (1-3)
* @param epoch Epoch when update occurred
*/
event TopContributorsUpdated(
address indexed boardAddress, address indexed contributor, uint256 inspirationCount, uint256 rank, uint256 epoch
);
event BoardManagerUpdated(address indexed oldBoardManager, address indexed newBoardManager);
event AddressExcluded(address indexed account);
event AddressIncluded(address indexed account);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Thrown when inspiration threshold is set to zero
error InvalidThreshold();
/// @dev Thrown when trying to register a board that's already registered
error BoardAlreadyRegistered();
/// @dev Thrown when trying to register a board with zero address as creator
error CreatorCannotBeZeroAddress();
/// @dev Thrown when board creator tries to set themselves as inspirer
error CreatorCannotBeOwnInspirer();
/// @dev Thrown when non-creator tries to set inspirer for a board
error OnlyBoardCreatorCanSetInspirer();
/// @dev only a board hook can register a board
error OnlyBoardManagerCanRegisterBoard();
error InvalidBoardManager();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ADMIN FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/**
* @dev Add address to excluded addresses list
* @param account Address to exclude
*/
function addExcludedAddress(address account) external;
/**
* @dev Remove address from excluded addresses list
* @param account Address to remove from exclusion
*/
function removeExcludedAddress(address account) external;
/**
* @dev Set inspiration threshold for tracking
* @param _newThreshold New threshold value
*/
function setInspirationThreshold(uint256 _newThreshold) external;
/**
* @dev Increment global epoch for all boards
*/
function incrementEpoch() external;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INSPIRATION SETTINGS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/**
* @dev Register a board with its creator and optional inspirer
* @param boardAddress Address of the board token
* @param creator Address of the board creator
* @param inspirer Address of the designated inspirer (can be address(0) if not set)
*/
function registerBoard(address boardAddress, address creator, address inspirer) external;
/**
* @dev Update the inspirer for a board (only callable by board creator)
* @param boardAddress Address of the board token
* @param newInspirer Address of the new inspirer
*/
function setInspirer(address boardAddress, address newInspirer) external;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INSPIRATION TRACKING */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/**
* @dev Check if inspiration conditions are met
* @param contributor Address sending the transfer (potential inspirer)
* @param amount Amount being transferred
* @return bool True if inspiration should be tracked
*/
function shouldInspire(address contributor, uint256 amount) external view returns (bool);
/**
* @dev Track inspiration relationship (called automatically by Board transfers)
* @param contributor Address of the inspiring user (sender)
* @param inspired Address of the user being inspired (recipient)
* @param amount Amount involved in the inspiration transaction
* @return bool True if inspiration was successfully tracked
*/
function tryInspire(address contributor, address inspired, uint256 amount) external returns (bool);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* VIEW FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/**
* @dev Check if a wallet has sufficient balance to be considered active
* @param wallet Address to check
* @return bool True if wallet is active, false otherwise
*/
function isActiveWallet(address wallet) external view returns (bool);
/**
* @dev Get the fee recipient (inspirer) for a board
* @param boardAddress Address of the board
* @return inspirer Address of the fee recipient
*/
function inspiredFeeRecipient(address boardAddress) external view returns (address inspirer);
/**
* @dev Get comprehensive board information
* @param boardAddress Address of the board
* @return creator Address of the board creator
* @return designatedInspirer Address of the designated inspirer
* @return currentTopContributor Address of the top contributor for current epoch
* @return currentTopContributorCount Count of unique active users inspired by top contributor in current epoch
* @return epoch Current epoch for the contract
*/
function getBoardInfo(address boardAddress)
external
view
returns (
address creator,
address designatedInspirer,
address currentTopContributor,
uint256 currentTopContributorCount,
uint256 epoch
);
/**
* @dev Check if an address has an inspiration relationship with a board
* @param boardAddress Address of the board
* @param user Address to check
* @return bool True if user is the designated inspirer or top contributor in current epoch
*/
function isInspired(address boardAddress, address user) external view returns (bool);
/**
* @dev Get inspiration count for a specific contributor on a board in current epoch
* @param boardAddress Address of the board
* @param contributor Address of the contributor
* @return count Number of unique active users this contributor has inspired in current epoch
*/
function getInspirationCount(address boardAddress, address contributor) external view returns (uint256 count);
/**
* @dev Get inspiration count for a specific contributor on a board in specific epoch
* @param boardAddress Address of the board
* @param epoch Epoch to check
* @param contributor Address of the contributor
* @return count Number of unique active users this contributor has inspired in specified epoch
*/
function getInspirationCount(
address boardAddress,
uint256 epoch,
address contributor
)
external
view
returns (uint256 count);
/**
* @dev Check if a contributor has already inspired a specific recipient in current epoch
* @param boardAddress Address of the board
* @param contributor Address of the contributor
* @param inspired Address of the inspired user
* @return bool True if inspiration has occurred before in current epoch
*/
function hasInspired(address boardAddress, address contributor, address inspired) external view returns (bool);
/**
* @dev Check if a contributor has already inspired a specific recipient in specific epoch
* @param boardAddress Address of the board
* @param epoch Epoch to check
* @param contributor Address of the contributor
* @param inspired Address of the inspired user
* @return bool True if inspiration has occurred before in specified epoch
*/
function hasInspired(
address boardAddress,
uint256 epoch,
address contributor,
address inspired
)
external
view
returns (bool);
/**
* @dev Get top 3 contributors for a board in current epoch
* @param boardAddress Address of the board
* @return topThree Array of top 3 contributor addresses
*/
function getTopContributors(address boardAddress) external view returns (address[3] memory topThree);
/**
* @dev Get top 3 contributors for a board in specific epoch
* @param boardAddress Address of the board
* @param epoch Epoch to check
* @return topThree Array of top 3 contributor addresses
*/
function getTopContributors(
address boardAddress,
uint256 epoch
)
external
view
returns (address[3] memory topThree);
function setBoardManager(address _boardManager) external;
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
interface IFeeExemptions {
error FeeExemptionInvalid(uint24 _invalidFee, uint24 _maxFee);
error NoBeneficiaryExemption(address _beneficiary, PoolId _poolId);
/// Emitted when a beneficiary exemption is set or updated for a specific pool
event BeneficiaryFeeSet(address indexed _beneficiary, PoolId indexed _poolId, uint24 _flatFee);
/// Emitted when a beneficiary exemption is removed from a specific pool
event BeneficiaryFeeRemoved(address indexed _beneficiary, PoolId indexed _poolId);
/**
* Defines the fee exemption that a beneficiary will receive if enabled.
*
* @member flatFee The flat fee value that the `_beneficiary` will receive
* @member enabled If the exemption is enabled
*/
struct FeeExemption {
uint24 flatFee;
bool enabled;
}
/// Get fee exemption for a specific beneficiary and pool
function feeExemption(address _beneficiary, PoolId _poolId) external view returns (FeeExemption memory);
/// Set fee exemption for a specific beneficiary and pool
function setFeeExemption(address _beneficiary, PoolId _poolId, uint24 _flatFee) external;
/// Remove fee exemption for a specific beneficiary and pool
function removeFeeExemption(address _beneficiary, PoolId _poolId) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0 = a * b; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
assembly ("memory-safe") {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly ("memory-safe") {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (0 - denominator) & denominator;
// Divide denominator by power of two
assembly ("memory-safe") {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly ("memory-safe") {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly ("memory-safe") {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the preconditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) != 0) {
require(++result > 0);
}
}
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
import "../../src/libraries/FullMath.sol";
import "../../src/libraries/FixedPoint96.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x, "liquidity overflow");
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount0)
internal
pure
returns (uint128 liquidity)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
uint256 intermediate = FullMath.mulDiv(sqrtPriceAX96, sqrtPriceBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtPriceBX96 - sqrtPriceAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount1)
internal
pure
returns (uint128 liquidity)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtPriceBX96 - sqrtPriceAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtPriceX96 A sqrt price representing the current pool prices
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtPriceX96,
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
if (sqrtPriceX96 <= sqrtPriceAX96) {
liquidity = getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, amount0);
} else if (sqrtPriceX96 < sqrtPriceBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtPriceX96, sqrtPriceBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity)
internal
pure
returns (uint256 amount0)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtPriceBX96 - sqrtPriceAX96, sqrtPriceBX96
) / sqrtPriceAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity)
internal
pure
returns (uint256 amount1)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtPriceX96 A sqrt price representing the current pool prices
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtPriceX96,
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
if (sqrtPriceX96 <= sqrtPriceAX96) {
amount0 = getAmount0ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
} else if (sqrtPriceX96 < sqrtPriceBX96) {
amount0 = getAmount0ForLiquidity(sqrtPriceX96, sqrtPriceBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
using CustomRevert for bytes4;
/// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
error InvalidTick(int24 tick);
/// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
error InvalidSqrtPrice(uint160 sqrtPriceX96);
/// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MAX_TICK = 887272;
/// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
int24 internal constant MIN_TICK_SPACING = 1;
/// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
int24 internal constant MAX_TICK_SPACING = type(int16).max;
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
1461446703485210103287273052203988822378723970342 - 4295128739 - 1;
/// @notice Given a tickSpacing, compute the maximum usable tick
function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MAX_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Given a tickSpacing, compute the minimum usable tick
function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MIN_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick;
assembly ("memory-safe") {
tick := signextend(2, tick)
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);
// The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
// is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer
// Equivalent to:
// price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
// or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
uint256 price;
assembly ("memory-safe") {
price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
}
if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;
assembly ("memory-safe") {
// if (tick > 0) price = type(uint256).max / price;
if sgt(tick, 0) { price := div(not(0), price) }
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtPrice of the output price is always consistent
// `sub(shl(32, 1), 1)` is `type(uint32).max`
// `price + type(uint32).max` will not overflow because `price` fits in 192 bits
sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
}
}
}
/// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
// second inequality must be >= because the price can never reach the price at the max tick
// if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
// if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
}
uint256 price = uint256(sqrtPriceX96) << 32;
uint256 r = price;
uint256 msb = BitMath.mostSignificantBit(r);
if (msb >= 128) r = price >> (msb - 127);
else r = price << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number
// Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
// Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
// sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
// is changed, this may need to be changed too
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Gas optimized verification of proof of inclusion for a leaf in a Merkle tree.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/MerkleProofLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/MerkleProofLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/MerkleProof.sol)
library MerkleProofLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MERKLE PROOF VERIFICATION OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether `leaf` exists in the Merkle tree with `root`, given `proof`.
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf)
internal
pure
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
if mload(proof) {
// Initialize `offset` to the offset of `proof` elements in memory.
let offset := add(proof, 0x20)
// Left shift by 5 is equivalent to multiplying by 0x20.
let end := add(offset, shl(5, mload(proof)))
// Iterate over proof elements to compute root hash.
for {} 1 {} {
// Slot of `leaf` in scratch space.
// If the condition is true: 0x20, otherwise: 0x00.
let scratch := shl(5, gt(leaf, mload(offset)))
// Store elements to hash contiguously in scratch space.
// Scratch space is 64 bytes (0x00 - 0x3f) and both elements are 32 bytes.
mstore(scratch, leaf)
mstore(xor(scratch, 0x20), mload(offset))
// Reuse `leaf` to store the hash to reduce stack operations.
leaf := keccak256(0x00, 0x40)
offset := add(offset, 0x20)
if iszero(lt(offset, end)) { break }
}
}
isValid := eq(leaf, root)
}
}
/// @dev Returns whether `leaf` exists in the Merkle tree with `root`, given `proof`.
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf)
internal
pure
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
if proof.length {
// Left shift by 5 is equivalent to multiplying by 0x20.
let end := add(proof.offset, shl(5, proof.length))
// Initialize `offset` to the offset of `proof` in the calldata.
let offset := proof.offset
// Iterate over proof elements to compute root hash.
for {} 1 {} {
// Slot of `leaf` in scratch space.
// If the condition is true: 0x20, otherwise: 0x00.
let scratch := shl(5, gt(leaf, calldataload(offset)))
// Store elements to hash contiguously in scratch space.
// Scratch space is 64 bytes (0x00 - 0x3f) and both elements are 32 bytes.
mstore(scratch, leaf)
mstore(xor(scratch, 0x20), calldataload(offset))
// Reuse `leaf` to store the hash to reduce stack operations.
leaf := keccak256(0x00, 0x40)
offset := add(offset, 0x20)
if iszero(lt(offset, end)) { break }
}
}
isValid := eq(leaf, root)
}
}
/// @dev Returns whether all `leaves` exist in the Merkle tree with `root`,
/// given `proof` and `flags`.
///
/// Note:
/// - Breaking the invariant `flags.length == (leaves.length - 1) + proof.length`
/// will always return false.
/// - The sum of the lengths of `proof` and `leaves` must never overflow.
/// - Any non-zero word in the `flags` array is treated as true.
/// - The memory offset of `proof` must be non-zero
/// (i.e. `proof` is not pointing to the scratch space).
function verifyMultiProof(
bytes32[] memory proof,
bytes32 root,
bytes32[] memory leaves,
bool[] memory flags
) internal pure returns (bool isValid) {
// Rebuilds the root by consuming and producing values on a queue.
// The queue starts with the `leaves` array, and goes into a `hashes` array.
// After the process, the last element on the queue is verified
// to be equal to the `root`.
//
// The `flags` array denotes whether the sibling
// should be popped from the queue (`flag == true`), or
// should be popped from the `proof` (`flag == false`).
/// @solidity memory-safe-assembly
assembly {
// Cache the lengths of the arrays.
let leavesLength := mload(leaves)
let proofLength := mload(proof)
let flagsLength := mload(flags)
// Advance the pointers of the arrays to point to the data.
leaves := add(0x20, leaves)
proof := add(0x20, proof)
flags := add(0x20, flags)
// If the number of flags is correct.
for {} eq(add(leavesLength, proofLength), add(flagsLength, 1)) {} {
// For the case where `proof.length + leaves.length == 1`.
if iszero(flagsLength) {
// `isValid = (proof.length == 1 ? proof[0] : leaves[0]) == root`.
isValid := eq(mload(xor(leaves, mul(xor(proof, leaves), proofLength))), root)
break
}
// The required final proof offset if `flagsLength` is not zero, otherwise zero.
let proofEnd := add(proof, shl(5, proofLength))
// We can use the free memory space for the queue.
// We don't need to allocate, since the queue is temporary.
let hashesFront := mload(0x40)
// Copy the leaves into the hashes.
// Sometimes, a little memory expansion costs less than branching.
// Should cost less, even with a high free memory offset of 0x7d00.
leavesLength := shl(5, leavesLength)
for { let i := 0 } iszero(eq(i, leavesLength)) { i := add(i, 0x20) } {
mstore(add(hashesFront, i), mload(add(leaves, i)))
}
// Compute the back of the hashes.
let hashesBack := add(hashesFront, leavesLength)
// This is the end of the memory for the queue.
// We recycle `flagsLength` to save on stack variables (sometimes save gas).
flagsLength := add(hashesBack, shl(5, flagsLength))
for {} 1 {} {
// Pop from `hashes`.
let a := mload(hashesFront)
// Pop from `hashes`.
let b := mload(add(hashesFront, 0x20))
hashesFront := add(hashesFront, 0x40)
// If the flag is false, load the next proof,
// else, pops from the queue.
if iszero(mload(flags)) {
// Loads the next proof.
b := mload(proof)
proof := add(proof, 0x20)
// Unpop from `hashes`.
hashesFront := sub(hashesFront, 0x20)
}
// Advance to the next flag.
flags := add(flags, 0x20)
// Slot of `a` in scratch space.
// If the condition is true: 0x20, otherwise: 0x00.
let scratch := shl(5, gt(a, b))
// Hash the scratch space and push the result onto the queue.
mstore(scratch, a)
mstore(xor(scratch, 0x20), b)
mstore(hashesBack, keccak256(0x00, 0x40))
hashesBack := add(hashesBack, 0x20)
if iszero(lt(hashesBack, flagsLength)) { break }
}
isValid :=
and(
// Checks if the last value in the queue is same as the root.
eq(mload(sub(hashesBack, 0x20)), root),
// And whether all the proofs are used, if required.
eq(proofEnd, proof)
)
break
}
}
}
/// @dev Returns whether all `leaves` exist in the Merkle tree with `root`,
/// given `proof` and `flags`.
///
/// Note:
/// - Breaking the invariant `flags.length == (leaves.length - 1) + proof.length`
/// will always return false.
/// - Any non-zero word in the `flags` array is treated as true.
/// - The calldata offset of `proof` must be non-zero
/// (i.e. `proof` is from a regular Solidity function with a 4-byte selector).
function verifyMultiProofCalldata(
bytes32[] calldata proof,
bytes32 root,
bytes32[] calldata leaves,
bool[] calldata flags
) internal pure returns (bool isValid) {
// Rebuilds the root by consuming and producing values on a queue.
// The queue starts with the `leaves` array, and goes into a `hashes` array.
// After the process, the last element on the queue is verified
// to be equal to the `root`.
//
// The `flags` array denotes whether the sibling
// should be popped from the queue (`flag == true`), or
// should be popped from the `proof` (`flag == false`).
/// @solidity memory-safe-assembly
assembly {
// If the number of flags is correct.
for {} eq(add(leaves.length, proof.length), add(flags.length, 1)) {} {
// For the case where `proof.length + leaves.length == 1`.
if iszero(flags.length) {
// `isValid = (proof.length == 1 ? proof[0] : leaves[0]) == root`.
// forgefmt: disable-next-item
isValid := eq(
calldataload(
xor(leaves.offset, mul(xor(proof.offset, leaves.offset), proof.length))
),
root
)
break
}
// The required final proof offset if `flagsLength` is not zero, otherwise zero.
let proofEnd := add(proof.offset, shl(5, proof.length))
// We can use the free memory space for the queue.
// We don't need to allocate, since the queue is temporary.
let hashesFront := mload(0x40)
// Copy the leaves into the hashes.
// Sometimes, a little memory expansion costs less than branching.
// Should cost less, even with a high free memory offset of 0x7d00.
calldatacopy(hashesFront, leaves.offset, shl(5, leaves.length))
// Compute the back of the hashes.
let hashesBack := add(hashesFront, shl(5, leaves.length))
// This is the end of the memory for the queue.
// We recycle `flagsLength` to save on stack variables (sometimes save gas).
flags.length := add(hashesBack, shl(5, flags.length))
// We don't need to make a copy of `proof.offset` or `flags.offset`,
// as they are pass-by-value (this trick may not always save gas).
for {} 1 {} {
// Pop from `hashes`.
let a := mload(hashesFront)
// Pop from `hashes`.
let b := mload(add(hashesFront, 0x20))
hashesFront := add(hashesFront, 0x40)
// If the flag is false, load the next proof,
// else, pops from the queue.
if iszero(calldataload(flags.offset)) {
// Loads the next proof.
b := calldataload(proof.offset)
proof.offset := add(proof.offset, 0x20)
// Unpop from `hashes`.
hashesFront := sub(hashesFront, 0x20)
}
// Advance to the next flag offset.
flags.offset := add(flags.offset, 0x20)
// Slot of `a` in scratch space.
// If the condition is true: 0x20, otherwise: 0x00.
let scratch := shl(5, gt(a, b))
// Hash the scratch space and push the result onto the queue.
mstore(scratch, a)
mstore(xor(scratch, 0x20), b)
mstore(hashesBack, keccak256(0x00, 0x40))
hashesBack := add(hashesBack, 0x20)
if iszero(lt(hashesBack, flags.length)) { break }
}
isValid :=
and(
// Checks if the last value in the queue is same as the root.
eq(mload(sub(hashesBack, 0x20)), root),
// And whether all the proofs are used, if required.
eq(proofEnd, proof.offset)
)
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EMPTY CALLDATA HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns an empty calldata bytes32 array.
function emptyProof() internal pure returns (bytes32[] calldata proof) {
/// @solidity memory-safe-assembly
assembly {
proof.length := 0
}
}
/// @dev Returns an empty calldata bytes32 array.
function emptyLeaves() internal pure returns (bytes32[] calldata leaves) {
/// @solidity memory-safe-assembly
assembly {
leaves.length := 0
}
}
/// @dev Returns an empty calldata bool array.
function emptyFlags() internal pure returns (bool[] calldata flags) {
/// @solidity memory-safe-assembly
assembly {
flags.length := 0
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Uniswap Hooks (last updated v0.1.0) (src/utils/CurrencySettler.sol)
// Copied from https://github.com/OpenZeppelin/uniswap-hooks/blob/master/src/utils/CurrencySettler.sol
pragma solidity ^0.8.24;
import { Currency } from "@uniswap/v4-core/src/types/Currency.sol";
import { IPoolManager } from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
/**
* @dev Library used to interact with the `PoolManager` to settle any open deltas.
* To settle a positive delta (a credit to the user), a user may take or mint.
* To settle a negative delta (a debt on the user), a user may transfer or burn to pay off a debt.
*
* Based on the https://github.com/Uniswap/v4-core/blob/main/test/utils/CurrencySettler.sol[Uniswap v4 test utils
* implementation].
*
* NOTE: Deltas are synced before any ERC-20 transfers in {settle} function.
*/
library CurrencySettler {
/**
* @notice Settle (pay) a currency to the `PoolManager`
* @param currency Currency to settle
* @param poolManager `PoolManager` to settle to
* @param payer Address of the payer, which can be the hook itself or an external address.
* @param amount Amount to send
* @param burn If true, burn the ERC-6909 token, otherwise transfer ERC-20 to the `PoolManager`
*/
function settle(Currency currency, IPoolManager poolManager, address payer, uint256 amount, bool burn) internal {
// Early return when amount is 0 given that some tokens may revert in this case
if (amount == 0) return;
// For native currencies or burns, calling sync is not required
// Short circuit for ERC-6909 burns to support ERC-6909-wrapped native tokens
if (burn) {
poolManager.burn(payer, currency.toId(), amount);
} else if (currency.isAddressZero()) {
poolManager.sync(currency);
poolManager.settle{ value: amount }();
} else {
poolManager.sync(currency);
if (payer != address(this)) {
IERC20(Currency.unwrap(currency)).transferFrom(payer, address(poolManager), amount);
} else {
IERC20(Currency.unwrap(currency)).transfer(address(poolManager), amount);
}
poolManager.settle();
}
}
/**
* @notice Take (receive) a currency from the `PoolManager`
* @param currency Currency to take
* @param poolManager `PoolManager` to take from
* @param recipient Address of the recipient of the ERC-6909 or ERC-20 token.
* @param amount Amount to receive
* @param claims If true, mint the ERC-6909 token, otherwise transfer ERC-20 from the `PoolManager` to recipient
*/
function take(
Currency currency,
IPoolManager poolManager,
address recipient,
uint256 amount,
bool claims
)
internal
{
// Early return when amount is 0 given that some tokens may revert in this case
if (amount == 0) return;
claims ? poolManager.mint(recipient, currency.toId(), amount) : poolManager.take(currency, recipient, amount);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
/**
* A helper library that finds the next valid tick for the specified tick spacing, starting
* from a single tick. This will allow us to round up or down to find it and also supports
* negative rounding.
*
* This is beneficial as it allows us to create positions directly next to the current tick.
*
* @dev This is used by `using TickFinder for int24;`
*/
library TickFinder {
/// The valid tick spacing value for the pool
int24 internal constant TICK_SPACING = 60;
/// Set our min/max tick range that is valid for the tick spacing
int24 internal constant MIN_TICK = -887_220;
int24 internal constant MAX_TICK = 887_220;
/**
* Helper function to find the nearest valid tick, rounding up or down.
*
* @param _tick The tick that we want to find a valid value for
* @param _roundDown If we want to round down (true) or up (false)
*
* return tick_ The valid tick
*/
function validTick(int24 _tick, bool _roundDown) internal pure returns (int24 tick_) {
// If we have a malformed tick, then we need to bring it back within range
if (_tick < MIN_TICK) _tick = MIN_TICK;
else if (_tick > MAX_TICK) _tick = MAX_TICK;
// If the tick is already valid, exit early
if (_tick % TICK_SPACING == 0) {
return _tick;
}
tick_ = _tick / TICK_SPACING * TICK_SPACING;
if (_tick < 0) {
tick_ -= TICK_SPACING;
}
// If we are rounding up, then we can just add a `TICK_SPACING` to the lower tick
if (!_roundDown) {
return tick_ + TICK_SPACING;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import { BeforeSwapDelta } from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import { BalanceDelta } from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import { IPoolManager } from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
interface IFairLaunch {
// Errors
error CannotModifyLiquidityDuringFairLaunch();
error CannotSellTokenDuringFairLaunch();
error NotBoardHook();
error ExceedsMaxAllocation(
address _sender, uint256 _requestedAmount, uint256 _maxAllocation, uint256 _alreadyPurchased
);
error InvalidLaunchParameters();
// Events
event FairLaunchCreated(PoolId indexed _poolId, uint256 _tokens, uint256 _startsAt, uint256 _endsAt);
event FairLaunchEnded(PoolId indexed _poolId, uint256 _revenue, uint256 _supply, uint256 _endedAt);
// Structs
struct FairLaunchInfo {
uint256 startsAt;
uint256 endsAt;
int24 initialTick;
uint256 revenue;
uint256 supply;
bool closed;
address phiEthToken;
uint256 initialTokenFairLaunch;
}
// Constants
function FAIR_LAUNCH_WINDOW() external pure returns (uint256);
// State Variables
function poolPhiEthToken(PoolId _poolId) external view returns (address);
// View Functions
function inFairLaunchWindow(PoolId _poolId) external view returns (bool);
function fairLaunchInfo(PoolId _poolId) external view returns (FairLaunchInfo memory);
// External Functions
function createPosition(
PoolId _poolId,
address _phiEthToken,
int24 _initialTick,
uint256 _publiphiesAt,
uint256 _initialTokenFairLaunch
)
external
returns (FairLaunchInfo memory);
function closePosition(
PoolKey memory _poolKey,
uint256 _tokenFees,
bool _nativeIsZero
)
external
returns (FairLaunchInfo memory);
function fillFromPosition(
PoolKey memory _poolKey,
int256 _amountSpecified,
bool _nativeIsZero,
address _sender,
uint256 maxAllocation
)
external
returns (BeforeSwapDelta beforeSwapDelta_, BalanceDelta balanceDelta_, FairLaunchInfo memory fairLaunchInfo_);
function modifyRevenue(PoolId _poolId, int256 _revenue) external;
function isWhitelisted(
address _sender,
bytes32 _merkleRoot,
bytes32[] calldata _proof,
uint256 _maxAllocation
)
external
pure
returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
/**
* Interface that a Subscriber contract should implement to receive updates from the Pupliphi
* {Notifier}.
*/
interface ISubscriber {
function subscribe(bytes memory data) external returns (bool);
function unsubscribe() external;
function notify(PoolId _poolId, bytes4 _key, bytes calldata _data) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
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)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";{
"remappings": [
"@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
"@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/community-contracts/=lib/openzeppelin-community-contracts/",
"@solady/=lib/solady/src/",
"@optimism/=lib/optimism/packages/contracts-bedrock/",
"forge-std/=lib/forge-std/src/",
"v4-periphery/=lib/v4-periphery/",
"@axelar-network/axelar-gmp-sdk-solidity/=lib/openzeppelin-community-contracts/lib/axelar-gmp-sdk-solidity/",
"@ensdomains/=lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin-contracts-upgradeable/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/",
"@openzeppelin-contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/",
"@zk-email/contracts/=lib/openzeppelin-community-contracts/lib/zk-email-verify/packages/contracts/",
"@zk-email/email-tx-builder/=lib/openzeppelin-community-contracts/lib/email-tx-builder/packages/contracts/",
"axelar-gmp-sdk-solidity/=lib/openzeppelin-community-contracts/lib/axelar-gmp-sdk-solidity/contracts/",
"ds-test/=lib/v4-periphery/lib/v4-core/lib/forge-std/lib/ds-test/src/",
"email-tx-builder/=lib/openzeppelin-community-contracts/lib/email-tx-builder/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"hardhat/=lib/v4-periphery/lib/v4-core/node_modules/hardhat/",
"kontrol-cheatcodes/=lib/optimism/packages/contracts-bedrock/lib/kontrol-cheatcodes/src/",
"lib-keccak/=lib/optimism/packages/contracts-bedrock/lib/lib-keccak/contracts/",
"openzeppelin-community-contracts/=lib/openzeppelin-community-contracts/contracts/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts-v5/=lib/optimism/packages/contracts-bedrock/lib/openzeppelin-contracts-v5/",
"openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
"optimism/=lib/optimism/",
"permit2/=lib/v4-periphery/lib/permit2/",
"safe-contracts/=lib/optimism/packages/contracts-bedrock/lib/safe-contracts/contracts/",
"solady-v0.0.245/=lib/optimism/packages/contracts-bedrock/lib/solady-v0.0.245/src/",
"solady/=lib/solady/src/",
"solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
"v4-core/=lib/v4-periphery/lib/v4-core/src/",
"zk-email-verify/=lib/openzeppelin-community-contracts/lib/zk-email-verify/"
],
"optimizer": {
"enabled": true,
"runs": 10
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "none",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": false
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_boardHook","type":"address"},{"internalType":"address","name":"_phiEthFactory","type":"address"},{"internalType":"address","name":"_boardManager","type":"address"},{"internalType":"address","name":"_poolSwap","type":"address"},{"internalType":"address","name":"_protocolOwner","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"InvalidAddress","type":"error"},{"inputs":[],"name":"InvalidBoardToken","type":"error"},{"inputs":[],"name":"MismatchedTokensAndLimits","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"_user","type":"address"},{"indexed":true,"internalType":"address","name":"_token","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"TokensAssigned","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_user","type":"address"},{"indexed":false,"internalType":"address","name":"_recipient","type":"address"},{"indexed":true,"internalType":"address","name":"_token","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"TokensClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_user","type":"address"},{"indexed":true,"internalType":"address","name":"_token","type":"address"},{"indexed":false,"internalType":"uint256","name":"_tokenIn","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_ethOut","type":"uint256"}],"name":"TokensSwapped","type":"event"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"},{"internalType":"address","name":"_token","type":"address"}],"name":"allocations","outputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"internalType":"address","name":"_user","type":"address"},{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"assignTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"boardManager","outputs":[{"internalType":"contract IBoardManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"_tokens","type":"address[]"},{"internalType":"uint160[]","name":"_sqrtPriceX96Limits","type":"uint160[]"},{"internalType":"address payable","name":"_recipient","type":"address"}],"name":"claimBoardAndSwap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_tokens","type":"address[]"},{"internalType":"address payable","name":"_recipient","type":"address"}],"name":"claimTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"phiEthFactory","outputs":[{"internalType":"contract IPhiEthFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolSwap","outputs":[{"internalType":"contract IPoolSwap","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_poolSwap","type":"address"}],"name":"setPoolSwap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]Contract Creation Code
0x608060405234801561000f575f5ffd5b506040516117d63803806117d683398101604081905261002e91610203565b806001600160a01b03811661005c57604051631e4fbdf760e01b81525f600482015260240160405180910390fd5b6100658161017d565b506001600160a01b03851661008d5760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0384166100b45760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0383166100db5760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0382166101025760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0381166101295760405163e6c4247b60e01b815260040160405180910390fd5b50600280546001600160a01b039586166001600160a01b0319918216179091556004805494861694821694909417909355600580549285169284169290921790915560038054919093169116179055610264565b600180546001600160a01b031916905561019681610199565b50565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b80516001600160a01b03811681146101fe575f5ffd5b919050565b5f5f5f5f5f60a08688031215610217575f5ffd5b610220866101e8565b945061022e602087016101e8565b935061023c604087016101e8565b925061024a606087016101e8565b9150610258608087016101e8565b90509295509295909350565b611565806102715f395ff3fe6080604052600436106100a4575f3560e01c806333809ad0146100af578063715018a6146100e4578063761032ec146100fa57806379ba509714610119578063853996e41461012d5780638da5cb5b146101715780639692e1ef14610185578063988a18f6146101a4578063b0f4c2ea146101c3578063d005aa6e146101e2578063e30c397814610201578063e448307d14610215578063f2fde38b14610234575f5ffd5b366100ab57005b5f5ffd5b3480156100ba575f5ffd5b506003546100ce906001600160a01b031681565b6040516100db919061121e565b60405180910390f35b3480156100ef575f5ffd5b506100f8610253565b005b348015610105575f5ffd5b506100f8610114366004611246565b610266565b348015610124575f5ffd5b506100f86102b7565b348015610138575f5ffd5b50610163610147366004611261565b600660209081525f928352604080842090915290825290205481565b6040519081526020016100db565b34801561017c575f5ffd5b506100ce6102ff565b348015610190575f5ffd5b506100f861019f3660046112df565b61030d565b3480156101af575f5ffd5b506100f86101be366004611360565b61073d565b3480156101ce575f5ffd5b506100f86101dd3660046113b2565b610977565b3480156101ed575f5ffd5b506004546100ce906001600160a01b031681565b34801561020c575f5ffd5b506100ce610a39565b348015610220575f5ffd5b506005546100ce906001600160a01b031681565b34801561023f575f5ffd5b506100f861024e366004611246565b610a48565b61025b610aae565b6102645f610ae0565b565b61026e610aae565b6001600160a01b0381166102955760405163e6c4247b60e01b815260040160405180910390fd5b600380546001600160a01b0319166001600160a01b0392909216919091179055565b33806102c1610a39565b6001600160a01b0316146102f3578060405163118cdaa760e01b81526004016102ea919061121e565b60405180910390fd5b6102fc81610ae0565b50565b5f546001600160a01b031690565b8382811461032e57604051639ff37e5d60e01b815260040160405180910390fd5b5f816001600160401b03811115610347576103476113f7565b604051908082528060200260200182016040528015610370578160200160208202803683370190505b5090505f826001600160401b0381111561038c5761038c6113f7565b6040519080825280602002602001820160405280156103b5578160200160208202803683370190505b5090505f805b8481101561072557604080516080810182525f8082526020820181905291810182905260608101919091528a8a838181106103f8576103f861140b565b905060200201602081019061040d9190611246565b6001600160a01b039081168252335f90815260066020908152604080832085519094168352929052818120549183018290520361044a575061071d565b335f90815260066020908152604080832084516001600160a01b0316845290915281205561049e818a8a858181106104845761048461140b565b90506020020160208101906104999190611246565b610af9565b6060820152600480548251604051635e5b3fbb60e01b81526001600160a01b0390921692635e5b3fbb926104d392910161121e565b602060405180830381865afa1580156104ee573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610512919061141f565b156105285780516001600160a01b031660208201525b5f805b848110156105a85782602001516001600160a01b03168782815181106105535761055361140b565b60200260200101516001600160a01b0316036105a05782606001518682815181106105805761058061140b565b602002602001018181516105949190611452565b905250600191506105a8565b60010161052b565b50806106155781602001518685815181106105c5576105c561140b565b60200260200101906001600160a01b031690816001600160a01b03168152505081606001518585815181106105fc576105fc61140b565b60209081029190910101528361061181611465565b9450505b815f01516001600160a01b0316336001600160a01b03165f5160206115395f395f51905f528a856040015160405161064e92919061147d565b60405180910390a3600480548351604051635e5b3fbb60e01b81526001600160a01b0390921692635e5b3fbb9261068692910161121e565b602060405180830381865afa1580156106a1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106c5919061141f565b61071a5781516040808401516060850151825191825260208201526001600160a01b039092169133917f25f1d03755df23c30e25db2dbd3891e31ce084bdfbfc46f9fe5e446ee5f9b2d4910160405180910390a35b50505b6001016103bb565b5061073283838388610eb9565b505050505050505050565b6001600160a01b0381166107645760405163e6c4247b60e01b815260040160405180910390fd5b5f5f5f5b8481101561096f578585828181106107825761078261140b565b90506020020160208101906107979190611246565b335f9081526006602090815260408083206001600160a01b03851684529091529020549093509150811561096757335f9081526006602090815260408083206001600160a01b038781168552925280832092909255600480549251635e5b3fbb60e01b81529290911691635e5b3fbb916108139187910161121e565b602060405180830381865afa15801561082e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610852919061141f565b1561092157604051632e1a7d4d60e01b8152600481018390526001600160a01b03841690632e1a7d4d906024015f604051808303815f87803b158015610896575f5ffd5b505af11580156108a8573d5f5f3e3d5ffd5b505050505f846001600160a01b0316836040515f6040518083038185875af1925050503d805f81146108f5576040519150601f19603f3d011682016040523d82523d5f602084013e6108fa565b606091505b505090508061091b5760405162461bcd60e51b81526004016102ea90611496565b5061092c565b61092c838584610ff1565b826001600160a01b0316336001600160a01b03165f5160206115395f395f51905f52868560405161095e92919061147d565b60405180910390a35b600101610768565b505050505050565b6002546001600160a01b031633146109a1576040516282b42960e81b815260040160405180910390fd5b8015610a33576001600160a01b038084165f908152600660209081526040808320938616835292905290812080548392906109dd908490611452565b92505081905550816001600160a01b0316836001600160a01b0316857fc733341be84ca8f5e6ee2be63797abe1af7bbe5efcb5c8abe995dc8a51fd4b3784604051610a2a91815260200190565b60405180910390a45b50505050565b6001546001600160a01b031690565b610a50610aae565b600180546001600160a01b0319166001600160a01b038316908117909155610a766102ff565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b33610ab76102ff565b6001600160a01b031614610264573360405163118cdaa760e01b81526004016102ea919061121e565b600180546001600160a01b03191690556102fc8161104e565b600480548351604051635e5b3fbb60e01b81525f936001600160a01b0390931692635e5b3fbb92610b2c9290910161121e565b602060405180830381865afa158015610b47573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b6b919061141f565b15610b7b57506040820151610eb3565b8251600354604080860151905163095ea7b360e01b81526001600160a01b039384169363095ea7b393610bb39391169160040161147d565b6020604051808303815f875af1158015610bcf573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bf3919061141f565b506005548351604051636036becb60e11b81526001600160a01b039092169163c06d7d9691610c249160040161121e565b602060405180830381865afa158015610c3f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c6391906114c3565b6001600160a01b031660208401819052610c9057604051632290e41360e01b815260040160405180910390fd5b602083015183516003546040805160a081019091526001600160a01b0393841692841692909210925f92911690631e2817de908085610cd3578860200151610cd6565b88515b6001600160a01b0316815260200185610cf0578851610cf6565b88602001515b6001600160a01b0390811682525f602080840191909152603c604080850191909152600254909216606093840152815192830182528715158352908a015190820190610d41906114de565b81526001600160a01b03808a16602092830152604080516001600160e01b031960e088901b16815285518316600482015285840151831660248201528582015162ffffff166044820152606086015160020b6064820152608090950151821660848601528351151560a48601529183015160c48501529101511660e4820152610104016020604051808303815f875af1158015610de0573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e0491906114f8565b90505f82610e1b57610e1682600f0b90565b610e25565b610e258260801d90565b600f0b610e31906114de565b90505f818760400151610e44919061150f565b90508015610e8557335f9081526006602090815260408083208a516001600160a01b0316845290915281208054839290610e7f908490611452565b90915550505b83610e9957610e948360801d90565b610ea3565b610ea383600f0b90565b6001600160801b03169450505050505b92915050565b5f805b83811015610f74575f868281518110610ed757610ed761140b565b602002602001015190505f868381518110610ef457610ef461140b565b602002602001015190505f811115610f6a57604051632e1a7d4d60e01b8152600481018290526001600160a01b03831690632e1a7d4d906024015f604051808303815f87803b158015610f45575f5ffd5b505af1158015610f57573d5f5f3e3d5ffd5b505050508084610f679190611452565b93505b5050600101610ebc565b508015610fea575f826001600160a01b0316826040515f6040518083038185875af1925050503d805f8114610fc4576040519150601f19603f3d011682016040523d82523d5f602084013e610fc9565b606091505b505090508061096f5760405162461bcd60e51b81526004016102ea90611496565b5050505050565b61104983846001600160a01b031663a9059cbb858560405160240161101792919061147d565b604051602081830303815290604052915060e01b6020820180516001600160e01b03838183161783525050505061109d565b505050565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b5f6110b16001600160a01b038416836110f5565b905080515f141580156110d55750808060200190518101906110d3919061141f565b155b156110495782604051635274afe760e01b81526004016102ea919061121e565b606061110283835f611109565b9392505050565b60608147101561112e573060405163cd78605960e01b81526004016102ea919061121e565b5f5f856001600160a01b031684866040516111499190611522565b5f6040518083038185875af1925050503d805f8114611183576040519150601f19603f3d011682016040523d82523d5f602084013e611188565b606091505b50915091506111988683836111a2565b9695505050505050565b6060826111b7576111b2826111f5565b611102565b81511580156111ce57506001600160a01b0384163b155b156111ee5783604051639996b31560e01b81526004016102ea919061121e565b5080611102565b8051156112055780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b6001600160a01b0391909116815260200190565b6001600160a01b03811681146102fc575f5ffd5b5f60208284031215611256575f5ffd5b813561110281611232565b5f5f60408385031215611272575f5ffd5b823561127d81611232565b9150602083013561128d81611232565b809150509250929050565b5f5f83601f8401126112a8575f5ffd5b5081356001600160401b038111156112be575f5ffd5b6020830191508360208260051b85010111156112d8575f5ffd5b9250929050565b5f5f5f5f5f606086880312156112f3575f5ffd5b85356001600160401b03811115611308575f5ffd5b61131488828901611298565b90965094505060208601356001600160401b03811115611332575f5ffd5b61133e88828901611298565b909450925050604086013561135281611232565b809150509295509295909350565b5f5f5f60408486031215611372575f5ffd5b83356001600160401b03811115611387575f5ffd5b61139386828701611298565b90945092505060208401356113a781611232565b809150509250925092565b5f5f5f5f608085870312156113c5575f5ffd5b8435935060208501356113d781611232565b925060408501356113e781611232565b9396929550929360600135925050565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b5f6020828403121561142f575f5ffd5b81518015158114611102575f5ffd5b634e487b7160e01b5f52601160045260245ffd5b80820180821115610eb357610eb361143e565b5f600182016114765761147661143e565b5060010190565b6001600160a01b03929092168252602082015260400190565b60208082526013908201527211551208151c985b9cd9995c8811985a5b1959606a1b604082015260600190565b5f602082840312156114d3575f5ffd5b815161110281611232565b5f600160ff1b82016114f2576114f261143e565b505f0390565b5f60208284031215611508575f5ffd5b5051919050565b81810381811115610eb357610eb361143e565b5f82518060208501845e5f92019182525091905056fe40b4b442b70a20081fa377001b642c7d3618847a45b5b8ed2b938e30a3299ddba164736f6c634300081e000a0000000000000000000000003aa3f28ae7c829a98359f31f3ddc5dae0a57afdc0000000000000000000000007c9e79683d018830b3a8bfaa1c7ea1b4835007d0000000000000000000000000e6c31d185c6fc0269bc60a041bb451fd3c2a9483000000000000000000000000a2326a10554fdfe5e36aa045ccb13ff12e5f130a0000000000000000000000006d83cac25cfacdc7035bed947b92b64e6a8b8090
Deployed Bytecode
0x6080604052600436106100a4575f3560e01c806333809ad0146100af578063715018a6146100e4578063761032ec146100fa57806379ba509714610119578063853996e41461012d5780638da5cb5b146101715780639692e1ef14610185578063988a18f6146101a4578063b0f4c2ea146101c3578063d005aa6e146101e2578063e30c397814610201578063e448307d14610215578063f2fde38b14610234575f5ffd5b366100ab57005b5f5ffd5b3480156100ba575f5ffd5b506003546100ce906001600160a01b031681565b6040516100db919061121e565b60405180910390f35b3480156100ef575f5ffd5b506100f8610253565b005b348015610105575f5ffd5b506100f8610114366004611246565b610266565b348015610124575f5ffd5b506100f86102b7565b348015610138575f5ffd5b50610163610147366004611261565b600660209081525f928352604080842090915290825290205481565b6040519081526020016100db565b34801561017c575f5ffd5b506100ce6102ff565b348015610190575f5ffd5b506100f861019f3660046112df565b61030d565b3480156101af575f5ffd5b506100f86101be366004611360565b61073d565b3480156101ce575f5ffd5b506100f86101dd3660046113b2565b610977565b3480156101ed575f5ffd5b506004546100ce906001600160a01b031681565b34801561020c575f5ffd5b506100ce610a39565b348015610220575f5ffd5b506005546100ce906001600160a01b031681565b34801561023f575f5ffd5b506100f861024e366004611246565b610a48565b61025b610aae565b6102645f610ae0565b565b61026e610aae565b6001600160a01b0381166102955760405163e6c4247b60e01b815260040160405180910390fd5b600380546001600160a01b0319166001600160a01b0392909216919091179055565b33806102c1610a39565b6001600160a01b0316146102f3578060405163118cdaa760e01b81526004016102ea919061121e565b60405180910390fd5b6102fc81610ae0565b50565b5f546001600160a01b031690565b8382811461032e57604051639ff37e5d60e01b815260040160405180910390fd5b5f816001600160401b03811115610347576103476113f7565b604051908082528060200260200182016040528015610370578160200160208202803683370190505b5090505f826001600160401b0381111561038c5761038c6113f7565b6040519080825280602002602001820160405280156103b5578160200160208202803683370190505b5090505f805b8481101561072557604080516080810182525f8082526020820181905291810182905260608101919091528a8a838181106103f8576103f861140b565b905060200201602081019061040d9190611246565b6001600160a01b039081168252335f90815260066020908152604080832085519094168352929052818120549183018290520361044a575061071d565b335f90815260066020908152604080832084516001600160a01b0316845290915281205561049e818a8a858181106104845761048461140b565b90506020020160208101906104999190611246565b610af9565b6060820152600480548251604051635e5b3fbb60e01b81526001600160a01b0390921692635e5b3fbb926104d392910161121e565b602060405180830381865afa1580156104ee573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610512919061141f565b156105285780516001600160a01b031660208201525b5f805b848110156105a85782602001516001600160a01b03168782815181106105535761055361140b565b60200260200101516001600160a01b0316036105a05782606001518682815181106105805761058061140b565b602002602001018181516105949190611452565b905250600191506105a8565b60010161052b565b50806106155781602001518685815181106105c5576105c561140b565b60200260200101906001600160a01b031690816001600160a01b03168152505081606001518585815181106105fc576105fc61140b565b60209081029190910101528361061181611465565b9450505b815f01516001600160a01b0316336001600160a01b03165f5160206115395f395f51905f528a856040015160405161064e92919061147d565b60405180910390a3600480548351604051635e5b3fbb60e01b81526001600160a01b0390921692635e5b3fbb9261068692910161121e565b602060405180830381865afa1580156106a1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106c5919061141f565b61071a5781516040808401516060850151825191825260208201526001600160a01b039092169133917f25f1d03755df23c30e25db2dbd3891e31ce084bdfbfc46f9fe5e446ee5f9b2d4910160405180910390a35b50505b6001016103bb565b5061073283838388610eb9565b505050505050505050565b6001600160a01b0381166107645760405163e6c4247b60e01b815260040160405180910390fd5b5f5f5f5b8481101561096f578585828181106107825761078261140b565b90506020020160208101906107979190611246565b335f9081526006602090815260408083206001600160a01b03851684529091529020549093509150811561096757335f9081526006602090815260408083206001600160a01b038781168552925280832092909255600480549251635e5b3fbb60e01b81529290911691635e5b3fbb916108139187910161121e565b602060405180830381865afa15801561082e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610852919061141f565b1561092157604051632e1a7d4d60e01b8152600481018390526001600160a01b03841690632e1a7d4d906024015f604051808303815f87803b158015610896575f5ffd5b505af11580156108a8573d5f5f3e3d5ffd5b505050505f846001600160a01b0316836040515f6040518083038185875af1925050503d805f81146108f5576040519150601f19603f3d011682016040523d82523d5f602084013e6108fa565b606091505b505090508061091b5760405162461bcd60e51b81526004016102ea90611496565b5061092c565b61092c838584610ff1565b826001600160a01b0316336001600160a01b03165f5160206115395f395f51905f52868560405161095e92919061147d565b60405180910390a35b600101610768565b505050505050565b6002546001600160a01b031633146109a1576040516282b42960e81b815260040160405180910390fd5b8015610a33576001600160a01b038084165f908152600660209081526040808320938616835292905290812080548392906109dd908490611452565b92505081905550816001600160a01b0316836001600160a01b0316857fc733341be84ca8f5e6ee2be63797abe1af7bbe5efcb5c8abe995dc8a51fd4b3784604051610a2a91815260200190565b60405180910390a45b50505050565b6001546001600160a01b031690565b610a50610aae565b600180546001600160a01b0319166001600160a01b038316908117909155610a766102ff565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b33610ab76102ff565b6001600160a01b031614610264573360405163118cdaa760e01b81526004016102ea919061121e565b600180546001600160a01b03191690556102fc8161104e565b600480548351604051635e5b3fbb60e01b81525f936001600160a01b0390931692635e5b3fbb92610b2c9290910161121e565b602060405180830381865afa158015610b47573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b6b919061141f565b15610b7b57506040820151610eb3565b8251600354604080860151905163095ea7b360e01b81526001600160a01b039384169363095ea7b393610bb39391169160040161147d565b6020604051808303815f875af1158015610bcf573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bf3919061141f565b506005548351604051636036becb60e11b81526001600160a01b039092169163c06d7d9691610c249160040161121e565b602060405180830381865afa158015610c3f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c6391906114c3565b6001600160a01b031660208401819052610c9057604051632290e41360e01b815260040160405180910390fd5b602083015183516003546040805160a081019091526001600160a01b0393841692841692909210925f92911690631e2817de908085610cd3578860200151610cd6565b88515b6001600160a01b0316815260200185610cf0578851610cf6565b88602001515b6001600160a01b0390811682525f602080840191909152603c604080850191909152600254909216606093840152815192830182528715158352908a015190820190610d41906114de565b81526001600160a01b03808a16602092830152604080516001600160e01b031960e088901b16815285518316600482015285840151831660248201528582015162ffffff166044820152606086015160020b6064820152608090950151821660848601528351151560a48601529183015160c48501529101511660e4820152610104016020604051808303815f875af1158015610de0573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e0491906114f8565b90505f82610e1b57610e1682600f0b90565b610e25565b610e258260801d90565b600f0b610e31906114de565b90505f818760400151610e44919061150f565b90508015610e8557335f9081526006602090815260408083208a516001600160a01b0316845290915281208054839290610e7f908490611452565b90915550505b83610e9957610e948360801d90565b610ea3565b610ea383600f0b90565b6001600160801b03169450505050505b92915050565b5f805b83811015610f74575f868281518110610ed757610ed761140b565b602002602001015190505f868381518110610ef457610ef461140b565b602002602001015190505f811115610f6a57604051632e1a7d4d60e01b8152600481018290526001600160a01b03831690632e1a7d4d906024015f604051808303815f87803b158015610f45575f5ffd5b505af1158015610f57573d5f5f3e3d5ffd5b505050508084610f679190611452565b93505b5050600101610ebc565b508015610fea575f826001600160a01b0316826040515f6040518083038185875af1925050503d805f8114610fc4576040519150601f19603f3d011682016040523d82523d5f602084013e610fc9565b606091505b505090508061096f5760405162461bcd60e51b81526004016102ea90611496565b5050505050565b61104983846001600160a01b031663a9059cbb858560405160240161101792919061147d565b604051602081830303815290604052915060e01b6020820180516001600160e01b03838183161783525050505061109d565b505050565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b5f6110b16001600160a01b038416836110f5565b905080515f141580156110d55750808060200190518101906110d3919061141f565b155b156110495782604051635274afe760e01b81526004016102ea919061121e565b606061110283835f611109565b9392505050565b60608147101561112e573060405163cd78605960e01b81526004016102ea919061121e565b5f5f856001600160a01b031684866040516111499190611522565b5f6040518083038185875af1925050503d805f8114611183576040519150601f19603f3d011682016040523d82523d5f602084013e611188565b606091505b50915091506111988683836111a2565b9695505050505050565b6060826111b7576111b2826111f5565b611102565b81511580156111ce57506001600160a01b0384163b155b156111ee5783604051639996b31560e01b81526004016102ea919061121e565b5080611102565b8051156112055780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b6001600160a01b0391909116815260200190565b6001600160a01b03811681146102fc575f5ffd5b5f60208284031215611256575f5ffd5b813561110281611232565b5f5f60408385031215611272575f5ffd5b823561127d81611232565b9150602083013561128d81611232565b809150509250929050565b5f5f83601f8401126112a8575f5ffd5b5081356001600160401b038111156112be575f5ffd5b6020830191508360208260051b85010111156112d8575f5ffd5b9250929050565b5f5f5f5f5f606086880312156112f3575f5ffd5b85356001600160401b03811115611308575f5ffd5b61131488828901611298565b90965094505060208601356001600160401b03811115611332575f5ffd5b61133e88828901611298565b909450925050604086013561135281611232565b809150509295509295909350565b5f5f5f60408486031215611372575f5ffd5b83356001600160401b03811115611387575f5ffd5b61139386828701611298565b90945092505060208401356113a781611232565b809150509250925092565b5f5f5f5f608085870312156113c5575f5ffd5b8435935060208501356113d781611232565b925060408501356113e781611232565b9396929550929360600135925050565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b5f6020828403121561142f575f5ffd5b81518015158114611102575f5ffd5b634e487b7160e01b5f52601160045260245ffd5b80820180821115610eb357610eb361143e565b5f600182016114765761147661143e565b5060010190565b6001600160a01b03929092168252602082015260400190565b60208082526013908201527211551208151c985b9cd9995c8811985a5b1959606a1b604082015260600190565b5f602082840312156114d3575f5ffd5b815161110281611232565b5f600160ff1b82016114f2576114f261143e565b505f0390565b5f60208284031215611508575f5ffd5b5051919050565b81810381811115610eb357610eb361143e565b5f82518060208501845e5f92019182525091905056fe40b4b442b70a20081fa377001b642c7d3618847a45b5b8ed2b938e30a3299ddba164736f6c634300081e000a
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.