pragma solidity ^0.8.0 ^0.8.13 ^0.8.20;
// lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
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);
}
// lib/openzeppelin-contracts/contracts/utils/Context.sol
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract 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;
}
}
// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// src/interfaces/IWETH.sol
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
// src/interfaces/IRouter.sol
interface IRouter {
struct Route {
address from;
address to;
bool stable;
address factory;
}
error ETHTransferFailed();
error Expired();
error InsufficientAmount();
error InsufficientAmountA();
error InsufficientAmountB();
error InsufficientAmountADesired();
error InsufficientAmountBDesired();
error InsufficientAmountAOptimal();
error InsufficientLiquidity();
error InsufficientOutputAmount();
error InvalidAmountInForETHDeposit();
error InvalidTokenInForETHDeposit();
error InvalidPath();
error InvalidRouteA();
error InvalidRouteB();
error OnlyWETH();
error PoolDoesNotExist();
error PoolFactoryDoesNotExist();
error SameAddresses();
error ZeroAddress();
/// @notice Address of FactoryRegistry.sol
function factoryRegistry() external view returns (address);
/// @notice Address of Protocol PoolFactory.sol
function defaultFactory() external view returns (address);
/// @notice Address of Voter.sol
function voter() external view returns (address);
/// @notice Interface of WETH contract used for WETH => ETH wrapping/unwrapping
function weth() external view returns (IWETH);
/// @dev Represents Ether. Used by zapper to determine whether to return assets as ETH/WETH.
function ETHER() external view returns (address);
/// @dev Struct containing information necessary to zap in and out of pools
/// @param tokenA .
/// @param tokenB .
/// @param stable Stable or volatile pool
/// @param factory factory of pool
/// @param amountOutMinA Minimum amount expected from swap leg of zap via routesA
/// @param amountOutMinB Minimum amount expected from swap leg of zap via routesB
/// @param amountAMin Minimum amount of tokenA expected from liquidity leg of zap
/// @param amountBMin Minimum amount of tokenB expected from liquidity leg of zap
struct Zap {
address tokenA;
address tokenB;
bool stable;
address factory;
uint256 amountOutMinA;
uint256 amountOutMinB;
uint256 amountAMin;
uint256 amountBMin;
}
/// @notice Sort two tokens by which address value is less than the other
/// @param tokenA Address of token to sort
/// @param tokenB Address of token to sort
/// @return token0 Lower address value between tokenA and tokenB
/// @return token1 Higher address value between tokenA and tokenB
function sortTokens(
address tokenA,
address tokenB
) external pure returns (address token0, address token1);
/// @notice Calculate the address of a pool by its' factory.
/// Used by all Router functions containing a `Route[]` or `_factory` argument.
/// Reverts if _factory is not approved by the FactoryRegistry
/// @dev Returns a randomly generated address for a nonexistent pool
/// @param tokenA Address of token to query
/// @param tokenB Address of token to query
/// @param stable True if pool is stable, false if volatile
/// @param _factory Address of factory which created the pool
function poolFor(
address tokenA,
address tokenB,
bool stable,
address _factory
) external view returns (address pool);
/// @notice Fetch and sort the reserves for a pool
/// @param tokenA .
/// @param tokenB .
/// @param stable True if pool is stable, false if volatile
/// @param _factory Address of PoolFactory for tokenA and tokenB
/// @return reserveA Amount of reserves of the sorted token A
/// @return reserveB Amount of reserves of the sorted token B
function getReserves(
address tokenA,
address tokenB,
bool stable,
address _factory
) external view returns (uint256 reserveA, uint256 reserveB);
/// @notice Perform chained getAmountOut calculations on any number of pools
function getAmountsOut(
uint256 amountIn,
Route[] memory routes
) external view returns (uint256[] memory amounts);
// **** ADD LIQUIDITY ****
/// @notice Quote the amount deposited into a Pool
/// @param tokenA .
/// @param tokenB .
/// @param stable True if pool is stable, false if volatile
/// @param _factory Address of PoolFactory for tokenA and tokenB
/// @param amountADesired Amount of tokenA desired to deposit
/// @param amountBDesired Amount of tokenB desired to deposit
/// @return amountA Amount of tokenA to actually deposit
/// @return amountB Amount of tokenB to actually deposit
/// @return liquidity Amount of liquidity token returned from deposit
function quoteAddLiquidity(
address tokenA,
address tokenB,
bool stable,
address _factory,
uint256 amountADesired,
uint256 amountBDesired
)
external
view
returns (uint256 amountA, uint256 amountB, uint256 liquidity);
/// @notice Quote the amount of liquidity removed from a Pool
/// @param tokenA .
/// @param tokenB .
/// @param stable True if pool is stable, false if volatile
/// @param _factory Address of PoolFactory for tokenA and tokenB
/// @param liquidity Amount of liquidity to remove
/// @return amountA Amount of tokenA received
/// @return amountB Amount of tokenB received
function quoteRemoveLiquidity(
address tokenA,
address tokenB,
bool stable,
address _factory,
uint256 liquidity
) external view returns (uint256 amountA, uint256 amountB);
/// @notice Add liquidity of two tokens to a Pool
/// @param tokenA .
/// @param tokenB .
/// @param stable True if pool is stable, false if volatile
/// @param amountADesired Amount of tokenA desired to deposit
/// @param amountBDesired Amount of tokenB desired to deposit
/// @param amountAMin Minimum amount of tokenA to deposit
/// @param amountBMin Minimum amount of tokenB to deposit
/// @param to Recipient of liquidity token
/// @param deadline Deadline to receive liquidity
/// @return amountA Amount of tokenA to actually deposit
/// @return amountB Amount of tokenB to actually deposit
/// @return liquidity Amount of liquidity token returned from deposit
function addLiquidity(
address tokenA,
address tokenB,
bool stable,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);
/// @notice Add liquidity of a token and WETH (transferred as ETH) to a Pool
/// @param token .
/// @param stable True if pool is stable, false if volatile
/// @param amountTokenDesired Amount of token desired to deposit
/// @param amountTokenMin Minimum amount of token to deposit
/// @param amountETHMin Minimum amount of ETH to deposit
/// @param to Recipient of liquidity token
/// @param deadline Deadline to add liquidity
/// @return amountToken Amount of token to actually deposit
/// @return amountETH Amount of tokenETH to actually deposit
/// @return liquidity Amount of liquidity token returned from deposit
function addLiquidityETH(
address token,
bool stable,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);
// **** REMOVE LIQUIDITY ****
/// @notice Remove liquidity of two tokens from a Pool
/// @param tokenA .
/// @param tokenB .
/// @param stable True if pool is stable, false if volatile
/// @param liquidity Amount of liquidity to remove
/// @param amountAMin Minimum amount of tokenA to receive
/// @param amountBMin Minimum amount of tokenB to receive
/// @param to Recipient of tokens received
/// @param deadline Deadline to remove liquidity
/// @return amountA Amount of tokenA received
/// @return amountB Amount of tokenB received
function removeLiquidity(
address tokenA,
address tokenB,
bool stable,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
/// @notice Remove liquidity of a token and WETH (returned as ETH) from a Pool
/// @param token .
/// @param stable True if pool is stable, false if volatile
/// @param liquidity Amount of liquidity to remove
/// @param amountTokenMin Minimum amount of token to receive
/// @param amountETHMin Minimum amount of ETH to receive
/// @param to Recipient of liquidity token
/// @param deadline Deadline to receive liquidity
/// @return amountToken Amount of token received
/// @return amountETH Amount of ETH received
function removeLiquidityETH(
address token,
bool stable,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
/// @notice Remove liquidity of a fee-on-transfer token and WETH (returned as ETH) from a Pool
/// @param token .
/// @param stable True if pool is stable, false if volatile
/// @param liquidity Amount of liquidity to remove
/// @param amountTokenMin Minimum amount of token to receive
/// @param amountETHMin Minimum amount of ETH to receive
/// @param to Recipient of liquidity token
/// @param deadline Deadline to receive liquidity
/// @return amountETH Amount of ETH received
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
bool stable,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
// **** SWAP ****
/// @notice Swap one token for another
/// @param amountIn Amount of token in
/// @param amountOutMin Minimum amount of desired token received
/// @param routes Array of trade routes used in the swap
/// @param to Recipient of the tokens received
/// @param deadline Deadline to receive tokens
/// @return amounts Array of amounts returned per route
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
Route[] calldata routes,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
/// @notice Swap ETH for a token
/// @param amountOutMin Minimum amount of desired token received
/// @param routes Array of trade routes used in the swap
/// @param to Recipient of the tokens received
/// @param deadline Deadline to receive tokens
/// @return amounts Array of amounts returned per route
function swapExactETHForTokens(
uint256 amountOutMin,
Route[] calldata routes,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
/// @notice Swap a token for WETH (returned as ETH)
/// @param amountIn Amount of token in
/// @param amountOutMin Minimum amount of desired ETH
/// @param routes Array of trade routes used in the swap
/// @param to Recipient of the tokens received
/// @param deadline Deadline to receive tokens
/// @return amounts Array of amounts returned per route
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
Route[] calldata routes,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
/// @notice Swap one token for another without slippage protection
/// @return amounts Array of amounts to swap per route
/// @param routes Array of trade routes used in the swap
/// @param to Recipient of the tokens received
/// @param deadline Deadline to receive tokens
function UNSAFE_swapExactTokensForTokens(
uint256[] memory amounts,
Route[] calldata routes,
address to,
uint256 deadline
) external returns (uint256[] memory);
// **** SWAP (supporting fee-on-transfer tokens) ****
/// @notice Swap one token for another supporting fee-on-transfer tokens
/// @param amountIn Amount of token in
/// @param amountOutMin Minimum amount of desired token received
/// @param routes Array of trade routes used in the swap
/// @param to Recipient of the tokens received
/// @param deadline Deadline to receive tokens
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
Route[] calldata routes,
address to,
uint256 deadline
) external;
/// @notice Swap ETH for a token supporting fee-on-transfer tokens
/// @param amountOutMin Minimum amount of desired token received
/// @param routes Array of trade routes used in the swap
/// @param to Recipient of the tokens received
/// @param deadline Deadline to receive tokens
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
Route[] calldata routes,
address to,
uint256 deadline
) external payable;
/// @notice Swap a token for WETH (returned as ETH) supporting fee-on-transfer tokens
/// @param amountIn Amount of token in
/// @param amountOutMin Minimum amount of desired ETH
/// @param routes Array of trade routes used in the swap
/// @param to Recipient of the tokens received
/// @param deadline Deadline to receive tokens
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
Route[] calldata routes,
address to,
uint256 deadline
) external;
/// @notice Zap a token A into a pool (B, C). (A can be equal to B or C).
/// Supports standard ERC20 tokens only (i.e. not fee-on-transfer tokens etc).
/// Slippage is required for the initial swap.
/// Additional slippage may be required when adding liquidity as the
/// price of the token may have changed.
/// @param tokenIn Token you are zapping in from (i.e. input token).
/// @param amountInA Amount of input token you wish to send down routesA
/// @param amountInB Amount of input token you wish to send down routesB
/// @param zapInPool Contains zap struct information. See Zap struct.
/// @param routesA Route used to convert input token to tokenA
/// @param routesB Route used to convert input token to tokenB
/// @param to Address you wish to mint liquidity to.
/// @param stake Auto-stake liquidity in corresponding gauge.
/// @return liquidity Amount of LP tokens created from zapping in.
function zapIn(
address tokenIn,
uint256 amountInA,
uint256 amountInB,
Zap calldata zapInPool,
Route[] calldata routesA,
Route[] calldata routesB,
address to,
bool stake
) external payable returns (uint256 liquidity);
/// @notice Zap out a pool (B, C) into A.
/// Supports standard ERC20 tokens only (i.e. not fee-on-transfer tokens etc).
/// Slippage is required for the removal of liquidity.
/// Additional slippage may be required on the swap as the
/// price of the token may have changed.
/// @param tokenOut Token you are zapping out to (i.e. output token).
/// @param liquidity Amount of liquidity you wish to remove.
/// @param zapOutPool Contains zap struct information. See Zap struct.
/// @param routesA Route used to convert tokenA into output token.
/// @param routesB Route used to convert tokenB into output token.
function zapOut(
address tokenOut,
uint256 liquidity,
Zap calldata zapOutPool,
Route[] calldata routesA,
Route[] calldata routesB
) external;
/// @notice Used to generate params required for zapping in.
/// Zap in => remove liquidity then swap.
/// Apply slippage to expected swap values to account for changes in reserves in between.
/// @dev Output token refers to the token you want to zap in from.
/// @param tokenA .
/// @param tokenB .
/// @param stable .
/// @param _factory .
/// @param amountInA Amount of input token you wish to send down routesA
/// @param amountInB Amount of input token you wish to send down routesB
/// @param routesA Route used to convert input token to tokenA
/// @param routesB Route used to convert input token to tokenB
/// @return amountOutMinA Minimum output expected from swapping input token to tokenA.
/// @return amountOutMinB Minimum output expected from swapping input token to tokenB.
/// @return amountAMin Minimum amount of tokenA expected from depositing liquidity.
/// @return amountBMin Minimum amount of tokenB expected from depositing liquidity.
function generateZapInParams(
address tokenA,
address tokenB,
bool stable,
address _factory,
uint256 amountInA,
uint256 amountInB,
Route[] calldata routesA,
Route[] calldata routesB
)
external
view
returns (
uint256 amountOutMinA,
uint256 amountOutMinB,
uint256 amountAMin,
uint256 amountBMin
);
/// @notice Used to generate params required for zapping out.
/// Zap out => swap then add liquidity.
/// Apply slippage to expected liquidity values to account for changes in reserves in between.
/// @dev Output token refers to the token you want to zap out of.
/// @param tokenA .
/// @param tokenB .
/// @param stable .
/// @param _factory .
/// @param liquidity Amount of liquidity being zapped out of into a given output token.
/// @param routesA Route used to convert tokenA into output token.
/// @param routesB Route used to convert tokenB into output token.
/// @return amountOutMinA Minimum output expected from swapping tokenA into output token.
/// @return amountOutMinB Minimum output expected from swapping tokenB into output token.
/// @return amountAMin Minimum amount of tokenA expected from withdrawing liquidity.
/// @return amountBMin Minimum amount of tokenB expected from withdrawing liquidity.
function generateZapOutParams(
address tokenA,
address tokenB,
bool stable,
address _factory,
uint256 liquidity,
Route[] calldata routesA,
Route[] calldata routesB
)
external
view
returns (
uint256 amountOutMinA,
uint256 amountOutMinB,
uint256 amountAMin,
uint256 amountBMin
);
/// @notice Used by zapper to determine appropriate ratio of A to B to deposit liquidity. Assumes stable pool.
/// @dev Returns stable liquidity ratio of B to (A + B).
/// E.g. if ratio is 0.4, it means there is more of A than there is of B.
/// Therefore you should deposit more of token A than B.
/// @param tokenA tokenA of stable pool you are zapping into.
/// @param tokenB tokenB of stable pool you are zapping into.
/// @param factory Factory that created stable pool.
/// @return ratio Ratio of token0 to token1 required to deposit into zap.
function quoteStableLiquidityRatio(
address tokenA,
address tokenB,
address factory
) external view returns (uint256 ratio);
}
// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/ERC20.sol)
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
// src/Token.sol
//import "forge-std/console2.sol";
contract Token is ERC20 {
constructor(
uint256 initialSupply,
string memory name,
string memory symbol
) ERC20(name, symbol) {
_mint(msg.sender, initialSupply);
}
}
// src/Payment.sol
contract Payment {
Token public token;
address public prizePool;
uint256 public poolFeePerc;
address public shield;
uint256 public shieldFeePerc;
IRouter router;
address public operator;
uint256 slippagePerc = 99;
event BuyIn(address indexed user, bytes32 hashedPrompt, uint256 amount);
constructor(
address tokenAddress,
address prizePoolAddress,
uint256 poolFeePerc_,
address shieldAddress,
uint256 shieldFeePerc_
) {
token = Token(tokenAddress);
router = IRouter(0xcF77a3Ba9A5CA399B7c97c74d54e5b1Beb874E43);
prizePool = payable(prizePoolAddress);
shield = payable(shieldAddress);
poolFeePerc = poolFeePerc_;
shieldFeePerc = shieldFeePerc_;
operator = msg.sender;
}
modifier isOperator() {
require(msg.sender == operator, "Only operator");
_;
}
function setOperator(address operator_) public isOperator {
operator = operator_;
}
function setAddress(
address prizePoolAddress,
address shieldAddress
) public isOperator {
prizePool = payable(prizePoolAddress);
shield = payable(shieldAddress);
}
function setFees(
uint256 poolFeePerc_,
uint256 shieldFeePerc_
) public isOperator {
require(
poolFeePerc_ + shieldFeePerc_ <= 100,
"Total fee cannot exceed 100%"
);
poolFeePerc = poolFeePerc_;
shieldFeePerc = shieldFeePerc_;
}
function applyFee(uint256 amount) private returns (uint256) {
uint256 poolFee = (amount * poolFeePerc) / 100;
uint256 shieldFee = (amount * shieldFeePerc) / 100;
if (poolFee > 0) {
(bool successPool, ) = prizePool.call{value: poolFee}("");
require(successPool, "Pool fee transfer failed");
}
if (shieldFee > 0) {
(bool successShield, ) = shield.call{value: shieldFee}("");
require(successShield, "Shield fee transfer failed");
}
return amount - poolFee - shieldFee;
}
function buyIn(bytes32 hashedPrompt) public payable {
uint256 amountIn = msg.value;
require(
amountIn > 0.0001 ether,
"Amount in must be greater than 0.0001 ether"
);
uint256 amountAfterFee = applyFee(amountIn);
//console2.log("amountAfterFee", amountAfterFee);
IRouter.Route[] memory routes = new IRouter.Route[](1);
routes[0] = IRouter.Route({
from: address(router.weth()),
to: address(token),
stable: false,
factory: address(router.defaultFactory())
});
// calculate price with slippage
uint256[] memory expectedAmounts = router.getAmountsOut(
amountIn,
routes
);
uint256 expectedOut = expectedAmounts[expectedAmounts.length - 1];
uint256 amountOutMin = (expectedOut * (100 - slippagePerc)) / 100;
//console2.log("amountOutMin", amountOutMin);
//@test
// uint256 amountOutMin = 1;
router.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: amountAfterFee
}(amountOutMin, routes, msg.sender, block.timestamp + 60 * 2);
emit BuyIn(msg.sender, hashedPrompt, amountIn);
}
fallback() external payable {
revert("Fallback function not supported");
}
receive() external payable {
revert("Receive function not supported");
}
}
{
"compilationTarget": {
"Payment.sol": "Payment"
},
"evmVersion": "cancun",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": false,
"runs": 200
},
"remappings": []
}
[{"inputs":[{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"address","name":"prizePoolAddress","type":"address"},{"internalType":"uint256","name":"poolFeePerc_","type":"uint256"},{"internalType":"address","name":"shieldAddress","type":"address"},{"internalType":"uint256","name":"shieldFeePerc_","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"bytes32","name":"hashedPrompt","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"BuyIn","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[{"internalType":"bytes32","name":"hashedPrompt","type":"bytes32"}],"name":"buyIn","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"operator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolFeePerc","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"prizePool","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"prizePoolAddress","type":"address"},{"internalType":"address","name":"shieldAddress","type":"address"}],"name":"setAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"poolFeePerc_","type":"uint256"},{"internalType":"uint256","name":"shieldFeePerc_","type":"uint256"}],"name":"setFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator_","type":"address"}],"name":"setOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"shield","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"shieldFeePerc","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token","outputs":[{"internalType":"contract Token","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]