Description:
Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/SwapHelper.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
interface IWBNB {
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
}
interface IPancakeV2Router {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactTokensForETH(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable returns (uint[] memory amounts);
}
interface IPancakeV3Router {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
}
interface IPancakeV2Factory {
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
interface IPancakeV2Pair {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function token0() external view returns (address);
}
interface IPancakeV3Factory {
function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool);
}
interface IPancakeV3Pool {
function slot0() external view returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
function liquidity() external view returns (uint128);
}
interface IPancakeV3QuoterV2 {
struct QuoteExactInputSingleParams {
address tokenIn;
address tokenOut;
uint256 amountIn;
uint24 fee;
uint160 sqrtPriceLimitX96;
}
function quoteExactInputSingle(QuoteExactInputSingleParams memory params)
external
returns (
uint256 amountOut,
uint160 sqrtPriceX96After,
uint32 initializedTicksCrossed,
uint256 gasEstimate
);
function quoteExactInput(bytes memory path, uint256 amountIn)
external
returns (
uint256 amountOut,
uint160[] memory sqrtPriceX96AfterList,
uint32[] memory initializedTicksCrossedList,
uint256 gasEstimate
);
}
contract SwapHelper {
using SafeERC20 for IERC20;
// Constants
uint256 private constant REFERRAL_FEE_BPS = 10; // 0.1% = 10 basis points
uint256 private constant BPS_BASE = 10000;
uint256 private constant DEADLINE_BUFFER = 60; // 1 minute
address private constant REFERRAL_ADDRESS = 0xB88276aB75113Eb8191B0e0A5D48f36B05AE6eD4;
// Immutable addresses
IPancakeV2Router public immutable v2Router;
IPancakeV3Router public immutable v3Router;
IPancakeV2Factory public immutable v2Factory;
IPancakeV3Factory public immutable v3Factory;
IPancakeV3QuoterV2 public immutable v3Quoter;
IWBNB public immutable wbnb;
// Custom errors
error NoPoolFound();
error InsufficientOutput();
error TransferFailed();
error InvalidInput();
// Events
event SwapExecuted(
address indexed tokenIn,
address indexed tokenOut,
uint256 amountIn,
uint256 amountOut,
string dexVersion
);
event ReferralFeeTaken(address indexed token, uint256 amount);
constructor(
address _v2Router,
address _v3Router,
address _v2Factory,
address _v3Factory,
address _v3Quoter,
address _wbnb
) {
require(_v2Router != address(0), "Invalid V2 router");
require(_v3Router != address(0), "Invalid V3 router");
require(_v2Factory != address(0), "Invalid V2 factory");
require(_v3Factory != address(0), "Invalid V3 factory");
require(_v3Quoter != address(0), "Invalid V3 quoter");
require(_wbnb != address(0), "Invalid WBNB");
v2Router = IPancakeV2Router(_v2Router);
v3Router = IPancakeV3Router(_v3Router);
v2Factory = IPancakeV2Factory(_v2Factory);
v3Factory = IPancakeV3Factory(_v3Factory);
v3Quoter = IPancakeV3QuoterV2(_v3Quoter);
wbnb = IWBNB(_wbnb);
}
receive() external payable {}
/**
* @dev Deducts referral fee from input amount and sends to referral address
*/
function _deductReferralFee(address token, uint256 amountIn) private returns (uint256) {
uint256 fee = (amountIn * REFERRAL_FEE_BPS) / BPS_BASE;
uint256 amountAfterFee = amountIn - fee;
if (fee > 0) {
if (token == address(0)) {
// Native BNB
(bool success, ) = REFERRAL_ADDRESS.call{value: fee}("");
if (!success) revert TransferFailed();
} else {
// ERC20 token
IERC20(token).safeTransfer(REFERRAL_ADDRESS, fee);
}
emit ReferralFeeTaken(token, fee);
}
return amountAfterFee;
}
/**
* @dev Safely approves token spending, resetting to 0 first
*/
function _safeApprove(address token, address spender, uint256 amount) private {
IERC20 erc = IERC20(token);
uint256 current = erc.allowance(address(this), spender);
if (current != 0) {
erc.safeApprove(spender, 0);
}
erc.safeApprove(spender, amount);
}
/**
* @dev Wraps native BNB to WBNB
*/
function _wrapBNB(uint256 amount) private {
wbnb.deposit{value: amount}();
}
/**
* @dev Unwraps WBNB to native BNB
*/
function _unwrapBNB(uint256 amount, address recipient) private {
wbnb.withdraw(amount);
(bool success, ) = recipient.call{value: amount}("");
if (!success) revert TransferFailed();
}
/**
* @dev Check if V2 pool exists for a pair
*/
function _v2PoolExists(address tokenA, address tokenB) private view returns (bool) {
address pair = v2Factory.getPair(tokenA, tokenB);
return pair != address(0);
}
/**
* @dev Check if V3 pool exists for a pair with specific fee
*/
function _v3PoolExists(address tokenA, address tokenB, uint24 fee) private view returns (bool) {
address pool = v3Factory.getPool(tokenA, tokenB, fee);
return pool != address(0);
}
/**
* @dev Swap using PancakeSwap V3 with single hop
*/
function swapV3(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint24 fee,
uint256 minOut,
address recipient
) public payable returns (uint256 amountOut) {
// Handle native BNB
address actualTokenIn = tokenIn == address(0) ? address(wbnb) : tokenIn;
address actualTokenOut = tokenOut == address(0) ? address(wbnb) : tokenOut;
bool unwrapOutput = tokenOut == address(0);
// Check if pool exists
if (!_v3PoolExists(actualTokenIn, actualTokenOut, fee)) {
revert NoPoolFound();
}
// Wrap BNB if needed
if (tokenIn == address(0)) {
if (msg.value != amountIn) revert InvalidInput();
_wrapBNB(amountIn);
}
// Approve router
_safeApprove(actualTokenIn, address(v3Router), amountIn);
// Prepare swap params
IPancakeV3Router.ExactInputSingleParams memory params = IPancakeV3Router.ExactInputSingleParams({
tokenIn: actualTokenIn,
tokenOut: actualTokenOut,
fee: fee,
recipient: unwrapOutput ? address(this) : recipient,
deadline: block.timestamp + DEADLINE_BUFFER,
amountIn: amountIn,
amountOutMinimum: minOut,
sqrtPriceLimitX96: 0
});
// Execute swap
amountOut = v3Router.exactInputSingle(params);
// Unwrap if needed
if (unwrapOutput) {
_unwrapBNB(amountOut, recipient);
}
emit SwapExecuted(tokenIn, tokenOut, amountIn, amountOut, "V3");
}
/**
* @dev Swap using PancakeSwap V2
*/
function swapV2(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minOut,
address recipient
) public payable returns (uint256 amountOut) {
// Handle native BNB
address actualTokenIn = tokenIn == address(0) ? address(wbnb) : tokenIn;
address actualTokenOut = tokenOut == address(0) ? address(wbnb) : tokenOut;
bool wrapInput = tokenIn == address(0);
bool unwrapOutput = tokenOut == address(0);
// Check if pool exists
if (!_v2PoolExists(actualTokenIn, actualTokenOut)) {
revert NoPoolFound();
}
// Wrap BNB if needed
if (wrapInput) {
if (msg.value != amountIn) revert InvalidInput();
_wrapBNB(amountIn);
}
// Approve router
_safeApprove(actualTokenIn, address(v2Router), amountIn);
// Prepare path
address[] memory path = new address[](2);
path[0] = actualTokenIn;
path[1] = actualTokenOut;
// Execute swap
uint[] memory amounts;
if (unwrapOutput) {
// Swap to WBNB then unwrap
amounts = v2Router.swapExactTokensForTokens(
amountIn,
minOut,
path,
address(this),
block.timestamp + DEADLINE_BUFFER
);
_unwrapBNB(amounts[amounts.length - 1], recipient);
} else {
amounts = v2Router.swapExactTokensForTokens(
amountIn,
minOut,
path,
recipient,
block.timestamp + DEADLINE_BUFFER
);
}
amountOut = amounts[amounts.length - 1];
emit SwapExecuted(tokenIn, tokenOut, amountIn, amountOut, "V2");
}
/**
* @dev Try swap through V3 with WBNB as middle hop
*/
function _tryV3WithHop(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint24 v3FeeToWBNB,
uint24 v3FeeFromWBNB,
uint256 minOut,
address recipient
) private returns (uint256 amountOut, bool success) {
// Handle native BNB output only (input is already normalized to WBNB)
address actualTokenIn = tokenIn;
address actualTokenOut = tokenOut == address(0) ? address(wbnb) : tokenOut;
bool unwrapOutput = tokenOut == address(0);
// Skip if already using WBNB
if (actualTokenIn == address(wbnb) || actualTokenOut == address(wbnb)) {
return (0, false);
}
// Check if both pools exist
if (!_v3PoolExists(actualTokenIn, address(wbnb), v3FeeToWBNB) ||
!_v3PoolExists(address(wbnb), actualTokenOut, v3FeeFromWBNB)) {
return (0, false);
}
// Approve router (no wrapping needed - input is already normalized)
_safeApprove(actualTokenIn, address(v3Router), amountIn);
// Encode path: tokenIn -> WBNB -> tokenOut
bytes memory path = abi.encodePacked(
actualTokenIn,
v3FeeToWBNB, // Use specific fee for first hop
address(wbnb),
v3FeeFromWBNB, // Use specific fee for second hop
actualTokenOut
);
IPancakeV3Router.ExactInputParams memory params = IPancakeV3Router.ExactInputParams({
path: path,
recipient: unwrapOutput ? address(this) : recipient,
deadline: block.timestamp + DEADLINE_BUFFER,
amountIn: amountIn,
amountOutMinimum: minOut
});
try v3Router.exactInput(params) returns (uint256 out) {
amountOut = out;
success = true;
// Unwrap if needed
if (unwrapOutput) {
_unwrapBNB(amountOut, recipient);
}
emit SwapExecuted(tokenIn, tokenOut, amountIn, amountOut, "V3-Hop");
} catch {
success = false;
}
}
/**
* @dev Try swap through V2 with WBNB as middle hop
*/
function _tryV2WithHop(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minOut,
address recipient
) private returns (uint256 amountOut, bool success) {
// Handle native BNB output only (input is already normalized to WBNB)
address actualTokenIn = tokenIn;
address actualTokenOut = tokenOut == address(0) ? address(wbnb) : tokenOut;
bool unwrapOutput = tokenOut == address(0);
// Skip if already using WBNB
if (actualTokenIn == address(wbnb) || actualTokenOut == address(wbnb)) {
return (0, false);
}
// Check if both pools exist
if (!_v2PoolExists(actualTokenIn, address(wbnb)) ||
!_v2PoolExists(address(wbnb), actualTokenOut)) {
return (0, false);
}
// Approve router (no wrapping needed - input is already normalized)
_safeApprove(actualTokenIn, address(v2Router), amountIn);
// Prepare path with WBNB hop
address[] memory path = new address[](3);
path[0] = actualTokenIn;
path[1] = address(wbnb);
path[2] = actualTokenOut;
try v2Router.swapExactTokensForTokens(
amountIn,
minOut,
path,
unwrapOutput ? address(this) : recipient,
block.timestamp + DEADLINE_BUFFER
) returns (uint[] memory amounts) {
amountOut = amounts[amounts.length - 1];
success = true;
// Unwrap if needed
if (unwrapOutput) {
_unwrapBNB(amountOut, recipient);
}
emit SwapExecuted(tokenIn, tokenOut, amountIn, amountOut, "V2-Hop");
} catch {
success = false;
}
}
/**
* @dev Best swap with automatic routing and referral fee
*/
function swapBest(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint24 v3FeeDirect, // for direct swap
uint24 v3FeeToWBNB, // for tokenIn → WBNB
uint24 v3FeeFromWBNB, // for WBNB → tokenOut
uint256 minOut,
address recipient
) external payable returns (uint256 amountOut) {
if (amountIn == 0 || recipient == address(0)) revert InvalidInput();
// Normalize input
address normalizedTokenIn = tokenIn;
uint256 normalizedAmountIn;
if (tokenIn == address(0)) {
if (msg.value != amountIn) revert InvalidInput();
// Fee taken from native balance the contract just received
uint256 afterFee = _deductReferralFee(address(0), amountIn);
// Wrap only the portion that will be traded
_wrapBNB(afterFee);
normalizedTokenIn = address(wbnb);
normalizedAmountIn = afterFee;
} else {
// Measure actual tokens received (supports deflationary tokens)
uint256 before = IERC20(tokenIn).balanceOf(address(this));
IERC20(tokenIn).safeTransferFrom(msg.sender, address(this), amountIn);
uint256 received = IERC20(tokenIn).balanceOf(address(this)) - before;
uint256 afterFee = _deductReferralFee(tokenIn, received);
normalizedAmountIn = afterFee;
}
address actualTokenOut = tokenOut == address(0) ? address(wbnb) : tokenOut;
// === NO-OP / WRAP / UNWRAP SHORT-CIRCUIT ===
if (normalizedTokenIn == actualTokenOut) {
// amountOut equals amountIn in a no-op
if (normalizedAmountIn < minOut) revert InsufficientOutput();
if (tokenOut == address(0)) {
// WBNB -> BNB
_unwrapBNB(normalizedAmountIn, recipient);
} else {
// ERC20 -> same ERC20 (including wrap-only BNB->WBNB case)
IERC20(actualTokenOut).safeTransfer(recipient, normalizedAmountIn);
}
emit SwapExecuted(tokenIn, tokenOut, normalizedAmountIn, normalizedAmountIn, "NOOP");
return normalizedAmountIn;
}
// Try V3 direct (no msg.value path anymore)
try this.swapV3(
normalizedTokenIn, tokenOut, normalizedAmountIn,
v3FeeDirect, minOut, recipient
) returns (uint256 out) {
return out;
} catch {
// Try V3 with WBNB hop (skips automatically if either side is WBNB)
(uint256 v3HopOut, bool v3HopSuccess) = _tryV3WithHop(
normalizedTokenIn, tokenOut, normalizedAmountIn,
v3FeeToWBNB, v3FeeFromWBNB, minOut, recipient
);
if (v3HopSuccess) return v3HopOut;
// Try V2 direct
try this.swapV2(
normalizedTokenIn, tokenOut, normalizedAmountIn,
minOut, recipient
) returns (uint256 out2) {
return out2;
} catch {
// Try V2 with WBNB hop
(uint256 v2HopOut, bool v2HopSuccess) = _tryV2WithHop(
normalizedTokenIn, tokenOut, normalizedAmountIn,
minOut, recipient
);
if (v2HopSuccess) return v2HopOut;
revert NoPoolFound();
}
}
}
/**
* @dev Get quote for V2 swap
* @param tokenIn Input token address (use address(0) for native BNB)
* @param tokenOut Output token address (use address(0) for native BNB)
* @param amountIn Input amount
* @return amountOut Expected output amount
* @return path The swap path used
*/
function getV2Quote(
address tokenIn,
address tokenOut,
uint256 amountIn
) public view returns (uint256 amountOut, address[] memory path) {
// Handle native BNB
address actualTokenIn = tokenIn == address(0) ? address(wbnb) : tokenIn;
address actualTokenOut = tokenOut == address(0) ? address(wbnb) : tokenOut;
// Deduct referral fee from input
uint256 amountInAfterFee = amountIn - (amountIn * REFERRAL_FEE_BPS / BPS_BASE);
// Try direct path first
path = new address[](2);
path[0] = actualTokenIn;
path[1] = actualTokenOut;
// Check if direct pair exists
address pair = v2Factory.getPair(actualTokenIn, actualTokenOut);
if (pair != address(0)) {
// Direct pair exists, calculate output
amountOut = _getV2AmountOut(amountInAfterFee, actualTokenIn, actualTokenOut, pair);
} else if (actualTokenIn != address(wbnb) && actualTokenOut != address(wbnb)) {
// Try path through WBNB
path = new address[](3);
path[0] = actualTokenIn;
path[1] = address(wbnb);
path[2] = actualTokenOut;
address pair1 = v2Factory.getPair(actualTokenIn, address(wbnb));
address pair2 = v2Factory.getPair(address(wbnb), actualTokenOut);
if (pair1 != address(0) && pair2 != address(0)) {
// Calculate output through WBNB
uint256 wbnbAmount = _getV2AmountOut(amountInAfterFee, actualTokenIn, address(wbnb), pair1);
amountOut = _getV2AmountOut(wbnbAmount, address(wbnb), actualTokenOut, pair2);
}
}
}
/**
* @dev Get quote for V3 swap using QuoterV2
* @param tokenIn Input token address (use address(0) for native BNB)
* @param tokenOut Output token address (use address(0) for native BNB)
* @param amountIn Input amount
* @param fee V3 pool fee tier (500, 2500, or 10000)
* @return amountOut Expected output amount
* @return poolExists Whether the pool exists
*/
function getV3Quote(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint24 fee
) public returns (uint256 amountOut, bool poolExists) {
// Handle native BNB
address actualTokenIn = tokenIn == address(0) ? address(wbnb) : tokenIn;
address actualTokenOut = tokenOut == address(0) ? address(wbnb) : tokenOut;
// Deduct referral fee from input
uint256 amountInAfterFee = amountIn - (amountIn * REFERRAL_FEE_BPS / BPS_BASE);
// Check if pool exists
address pool = v3Factory.getPool(actualTokenIn, actualTokenOut, fee);
if (pool == address(0)) {
return (0, false);
}
poolExists = true;
// Use QuoterV2 for accurate quote
try v3Quoter.quoteExactInputSingle(
IPancakeV3QuoterV2.QuoteExactInputSingleParams({
tokenIn: actualTokenIn,
tokenOut: actualTokenOut,
amountIn: amountInAfterFee,
fee: fee,
sqrtPriceLimitX96: 0
})
) returns (uint256 quotedAmount, uint160, uint32, uint256) {
amountOut = quotedAmount;
} catch {
// If quote fails, return 0 instead of reverting
amountOut = 0;
}
}
/**
* @dev Get quote for V3 multi-hop swap using QuoterV2
* @param tokenIn Input token address
* @param tokenOut Output token address
* @param amountIn Input amount
* @param feeToWBNB Fee for tokenIn -> WBNB hop
* @param feeFromWBNB Fee for WBNB -> tokenOut hop
* @return amountOut Expected output amount
*/
function _getV3HopQuote(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint24 feeToWBNB,
uint24 feeFromWBNB
) private returns (uint256 amountOut) {
// Skip if either token is WBNB
if (tokenIn == address(wbnb) || tokenOut == address(wbnb)) {
return 0;
}
// Encode path: tokenIn -> WBNB -> tokenOut
bytes memory path = abi.encodePacked(
tokenIn,
feeToWBNB,
address(wbnb),
feeFromWBNB,
tokenOut
);
try v3Quoter.quoteExactInput(path, amountIn)
returns (uint256 quotedAmount, uint160[] memory, uint32[] memory, uint256) {
return quotedAmount;
} catch {
return 0;
}
}
/**
* @dev Get best quote with automatic routing (mirrors swapBest logic)
* @param tokenIn Input token address (use address(0) for native BNB)
* @param tokenOut Output token address (use address(0) for native BNB)
* @param amountIn Input amount
* @param v3FeeDirect Fee tier for V3 direct swap (500, 2500, or 10000)
* @param v3FeeToWBNB Fee tier for V3 tokenIn -> WBNB hop
* @param v3FeeFromWBNB Fee tier for V3 WBNB -> tokenOut hop
* @return amountOut Best expected output amount found
* @return bestRoute The route that gives best output ("V3", "V3-Hop", "V2", "V2-Hop", or "NOOP")
*/
function getBestQuote(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint24 v3FeeDirect,
uint24 v3FeeToWBNB,
uint24 v3FeeFromWBNB
) public returns (uint256 amountOut, string memory bestRoute) {
if (amountIn == 0) return (0, "INVALID");
// Handle native BNB
address actualTokenIn = tokenIn == address(0) ? address(wbnb) : tokenIn;
address actualTokenOut = tokenOut == address(0) ? address(wbnb) : tokenOut;
// Deduct referral fee from input
uint256 amountInAfterFee = amountIn - (amountIn * REFERRAL_FEE_BPS / BPS_BASE);
// Check for no-op (same token in and out)
if (actualTokenIn == actualTokenOut) {
return (amountInAfterFee, "NOOP");
}
uint256 bestAmount = 0;
// Try V3 direct using QuoterV2
(uint256 v3DirectOut, bool v3Exists) = getV3Quote(tokenIn, tokenOut, amountIn, v3FeeDirect);
if (v3Exists && v3DirectOut > bestAmount) {
bestAmount = v3DirectOut;
bestRoute = "V3";
}
// Try V3 with WBNB hop using QuoterV2
if (actualTokenIn != address(wbnb) && actualTokenOut != address(wbnb)) {
uint256 v3HopOut = _getV3HopQuote(
actualTokenIn,
actualTokenOut,
amountInAfterFee,
v3FeeToWBNB,
v3FeeFromWBNB
);
if (v3HopOut > bestAmount) {
bestAmount = v3HopOut;
bestRoute = "V3-Hop";
}
}
// Try V2 direct
address v2Pair = v2Factory.getPair(actualTokenIn, actualTokenOut);
if (v2Pair != address(0)) {
uint256 v2DirectOut = _getV2AmountOut(amountInAfterFee, actualTokenIn, actualTokenOut, v2Pair);
if (v2DirectOut > bestAmount) {
bestAmount = v2DirectOut;
bestRoute = "V2";
}
}
// Try V2 with WBNB hop (skip if either token is already WBNB)
if (actualTokenIn != address(wbnb) && actualTokenOut != address(wbnb)) {
address v2Pair1 = v2Factory.getPair(actualTokenIn, address(wbnb));
address v2Pair2 = v2Factory.getPair(address(wbnb), actualTokenOut);
if (v2Pair1 != address(0) && v2Pair2 != address(0)) {
uint256 wbnbAmount = _getV2AmountOut(amountInAfterFee, actualTokenIn, address(wbnb), v2Pair1);
uint256 v2HopOut = _getV2AmountOut(wbnbAmount, address(wbnb), actualTokenOut, v2Pair2);
if (v2HopOut > bestAmount) {
bestAmount = v2HopOut;
bestRoute = "V2-Hop";
}
}
}
// Return best found (will be 0 if no route exists)
amountOut = bestAmount;
if (bestAmount == 0) {
bestRoute = "NO_POOL";
}
}
/**
* @dev Calculate V2 output amount using the constant product formula
*/
function _getV2AmountOut(
uint256 amountIn,
address tokenIn,
address tokenOut,
address pair
) private view returns (uint256) {
(uint112 reserve0, uint112 reserve1,) = IPancakeV2Pair(pair).getReserves();
address token0 = IPancakeV2Pair(pair).token0();
(uint112 reserveIn, uint112 reserveOut) = tokenIn == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
require(amountIn > 0, "Insufficient input amount");
require(reserveIn > 0 && reserveOut > 0, "Insufficient liquidity");
// PancakeSwap V2 fee is 0.25% (9975/10000)
uint256 amountInWithFee = amountIn * 9975;
uint256 numerator = amountInWithFee * reserveOut;
uint256 denominator = (reserveIn * 10000) + amountInWithFee;
return numerator / denominator;
}
}"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../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 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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @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);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @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.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(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, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* 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.isContract(address(token));
}
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface 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].
*/
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);
}
"
},
"lib/openzeppelin-contracts/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
"
}
},
"settings": {
"remappings": [
"ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"openzeppelin/=lib/openzeppelin-contracts/contracts/",
"v3-core/=lib/v3-core/",
"v3-periphery/=lib/v3-periphery/contracts/"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": true
}
}}
Submitted on: 2025-10-16 17:45:34
Comments
Log in to comment.
No comments yet.