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": {
"contracts/8/DagRouter.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import "./libraries/CommonLib.sol";
import "./libraries/UniversalERC20.sol";
import "./interfaces/IERC20.sol";
abstract contract DagRouter is CommonLib {
using UniversalERC20 for IERC20;
/// @notice Core DAG algorithm data structure
/// @dev Maintains the state of the DAG during execution
struct SwapState {
/// @notice the number of nodes need to be processed
uint256 nodeNum;
/// @notice the refundTo address of the DAG
address refundTo;
}
/// @notice The fromTokenAmount will not must be greater than 0, cause for some protocols the fromTokenAmount needs to be 0 to skip token transfer like fourmeme.
function _dagSwapInternal(
BaseRequest calldata baseRequest,
RouterPath[] calldata paths,
address payer,
address refundTo,
address receiver
) internal {
// 1. check and process ETH
BaseRequest memory _baseRequest = baseRequest;
address fromToken = _bytes32ToAddress(_baseRequest.fromToken);
address firstNodeToken = _bytes32ToAddress(paths[0].fromToken);
// In order to deal with ETH/WETH transfer rules in a unified manner,
// we do not need to judge according to fromToken.
if (IERC20(fromToken).isETH()) {
require(firstNodeToken == _WETH, "firstToken mismatch");
IWETH(_WETH).deposit{
value: _baseRequest.fromTokenAmount
}();
payer = address(this);
} else {
require(firstNodeToken == fromToken, "firstToken mismatch");
require(msg.value == 0, "value must be 0");
}
// 2. execute dag swap
_exeDagSwap(payer, receiver, refundTo, _baseRequest.fromTokenAmount, IERC20(_baseRequest.toToken).isETH(), paths);
// 3. transfer tokens to receiver
_transferTokenToUser(_baseRequest.toToken, receiver);
}
/// @notice The core logic to execute the DAG swap. For the first node, the payer should use passed value.
/// For the non-first node, the payer should always be address(this) cause the to address of the middle swap is address(this).
function _exeDagSwap(
address payer,
address receiver,
address refundTo,
uint256 firstNodeBalance,
bool isToNative,
RouterPath[] calldata paths
) private {
uint256 nodeNum = paths.length;
SwapState memory swapState = _initSwapState(nodeNum, refundTo);
// execute nodes
for (uint256 i = 0; i < nodeNum;) {
if (i != 0) { // reset payer for non-first node
payer = address(this);
}
_exeNode(payer, receiver, firstNodeBalance, i, isToNative, paths[i], swapState);
unchecked {
++i;
}
}
}
/// @notice Initialize the swap state for the DAG execution
function _initSwapState(
uint256 _nodeNum,
address _refundTo
) private pure returns (SwapState memory state) {
state.nodeNum = _nodeNum;
state.refundTo = _refundTo;
}
/// @notice The core logic to execute the each node
function _exeNode(
address payer,
address receiver,
uint256 nodeBalance,
uint256 nodeIndex,
bool isToNative,
RouterPath calldata path,
SwapState memory swapState
) private {
uint256 totalWeight;
uint256 accAmount;
address fromToken = _bytes32ToAddress(path.fromToken);
require(path.mixAdapters.length > 0, "edge length must be > 0");
require(
path.mixAdapters.length == path.rawData.length &&
path.mixAdapters.length == path.extraData.length &&
path.mixAdapters.length == path.assetTo.length,
"path length mismatch"
);
// to get the nodeBalance for non-first node, the balance of the first node is the original passed value
if (nodeIndex != 0) {
nodeBalance = IERC20(fromToken).balanceOf(address(this));
require(nodeBalance > 0, "node balance must be > 0");
}
// execute edges
for (uint256 i = 0; i < path.mixAdapters.length;) {
uint256 inputIndex;
uint256 outputIndex;
uint256 weight;
// 1. get inputIndex, outputIndex, weight and verify
{
bytes32 rawData = bytes32(path.rawData[i]);
assembly {
weight := shr(160, and(rawData, _WEIGHT_MASK))
inputIndex := shr(184, and(rawData, _INPUT_INDEX_MASK))
outputIndex := shr(176, and(rawData, _OUTPUT_INDEX_MASK))
}
require(inputIndex == nodeIndex, "node inputIndex inconsistent");
require(inputIndex < outputIndex && outputIndex <= swapState.nodeNum, "node index out of range");
totalWeight += weight;
if (i == path.mixAdapters.length - 1) {
require(
totalWeight == 10_000,
"totalWeight must be 10000"
);
}
}
// 2. transfer fromToken from payer to assetTo of edge
{
uint256 _fromTokenAmount;
if (i == path.mixAdapters.length - 1) {
_fromTokenAmount = nodeBalance - accAmount;
} else {
_fromTokenAmount = (nodeBalance * weight) / 10_000;
accAmount += _fromTokenAmount;
}
if (_fromTokenAmount > 0) {
_transferInternal(
payer,
path.assetTo[i],
path.fromToken,
_fromTokenAmount
);
}
}
// 3. execute single swap
{
address to = address(this);
if (outputIndex == swapState.nodeNum && !isToNative) {
to = receiver;
}
_exeEdge(
path.rawData[i],
path.mixAdapters[i],
path.extraData[i],
to,
swapState.refundTo
);
}
unchecked {
++i;
}
}
}
function _exeEdge(
uint256 rawData,
address mixAdapter,
bytes memory extraData,
address to,
address refundTo
) private {
bool reverse;
address poolAddress;
assembly {
poolAddress := and(rawData, _ADDRESS_MASK)
reverse := and(rawData, _REVERSE_MASK)
}
_exeAdapter(
reverse,
mixAdapter,
to,
poolAddress,
extraData,
refundTo
);
}
}"
},
"contracts/8/DexRouter.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import "./UnxswapRouter.sol";
import "./UnxswapV3Router.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/IApproveProxy.sol";
import "./interfaces/IWNativeRelayer.sol";
import "./libraries/PMMLib.sol";
import "./libraries/CommissionLib.sol";
import "./libraries/EthReceiver.sol";
import "./libraries/UniswapTokenInfoHelper.sol";
import "./libraries/CommonLib.sol";
import "./DagRouter.sol";
/// @title DexRouterV1
/// @notice Entrance of Split trading in Dex platform
/// @dev Entrance of Split trading in Dex platform
contract DexRouter is
EthReceiver,
UnxswapRouter,
UnxswapV3Router,
CommissionLib,
UniswapTokenInfoHelper,
DagRouter
{
string public constant version = "v1.0.6-dag";
using UniversalERC20 for IERC20;
//-------------------------------
//------- Modifier --------------
//-------------------------------
/// @notice Ensures a function is called before a specified deadline.
/// @param deadLine The UNIX timestamp deadline.
modifier isExpired(uint256 deadLine) {
require(deadLine >= block.timestamp, "Route: expired");
_;
}
//-------------------------------
//------- Internal Functions ----
//-------------------------------
/// @notice Executes multiple adapters for a transaction pair.
/// @param payer The address of the payer.
/// @param to The address of the receiver.
/// @param batchAmount The amount to be transferred in each batch.
/// @param path The routing path for the swap.
/// @param noTransfer A flag to indicate whether the token transfer should be skipped.
/// @dev It includes checks for the total weight of the paths and executes the swapping through the adapters.
function _exeForks(
address payer,
address refundTo,
address to,
uint256 batchAmount,
RouterPath memory path,
bool noTransfer
) private {
uint256 totalWeight;
for (uint256 i = 0; i < path.mixAdapters.length; i++) {
bytes32 rawData = bytes32(path.rawData[i]);
address poolAddress;
bool reverse;
{
uint256 weight;
assembly {
poolAddress := and(rawData, _ADDRESS_MASK)
reverse := and(rawData, _REVERSE_MASK)
weight := shr(160, and(rawData, _WEIGHT_MASK))
}
totalWeight += weight;
if (i == path.mixAdapters.length - 1) {
require(
totalWeight <= 10_000,
"totalWeight can not exceed 10000 limit"
);
}
if (!noTransfer) {
uint256 _fromTokenAmount = weight == 10_000
? batchAmount
: (batchAmount * weight) / 10_000;
_transferInternal(
payer,
path.assetTo[i],
path.fromToken,
_fromTokenAmount
);
}
}
_exeAdapter(
reverse,
path.mixAdapters[i],
to,
poolAddress,
path.extraData[i],
refundTo
);
}
}
/// @notice Executes a series of swaps or operations defined by a set of routing paths, potentially across different protocols or pools.
/// @param payer The address providing the tokens for the swap.
/// @param receiver The address receiving the output tokens.
/// @param isToNative Indicates whether the final asset should be converted to the native blockchain asset (e.g., ETH).
/// @param batchAmount The total amount of the input token to be swapped.
/// @param hops An array of RouterPath structures, each defining a segment of the swap route.
/// @dev This function manages complex swap routes that might involve multiple hops through different liquidity pools or swapping protocols.
/// It iterates through the provided `hops`, executing each segment of the route in sequence.
function _exeHop(
address payer,
address refundTo,
address receiver,
bool isToNative,
uint256 batchAmount,
RouterPath[] memory hops
) private {
address fromToken = _bytes32ToAddress(hops[0].fromToken);
bool toNext;
bool noTransfer;
// execute hop
uint256 hopLength = hops.length;
for (uint256 i = 0; i < hopLength; ) {
if (i > 0) {
fromToken = _bytes32ToAddress(hops[i].fromToken);
batchAmount = _getBalanceOf(fromToken, address(this));
payer = address(this);
}
address to = address(this);
if (i == hopLength - 1 && !isToNative) {
to = receiver;
} else if (i < hopLength - 1 && hops[i + 1].assetTo.length == 1) {
to = hops[i + 1].assetTo[0];
toNext = true;
} else {
toNext = false;
}
// 3.2 execute forks
_exeForks(payer, refundTo, to, batchAmount, hops[i], noTransfer);
noTransfer = toNext;
unchecked {
++i;
}
}
}
/// @notice Executes a complex swap based on provided parameters and paths.
/// @param baseRequest Basic swap details including tokens, amounts, and deadline.
/// @param batchesAmount Amounts for each swap batch.
/// @param batches Detailed swap paths for execution.
/// @param payer Address providing the tokens.
/// @param receiver Address receiving the swapped tokens.
function _smartSwapInternal(
BaseRequest memory baseRequest,
uint256[] memory batchesAmount,
RouterPath[][] memory batches,
address payer,
address refundTo,
address receiver
) private {
// 1. transfer from token in
BaseRequest memory _baseRequest = baseRequest;
address fromToken = _bytes32ToAddress(_baseRequest.fromToken);
// In order to deal with ETH/WETH transfer rules in a unified manner,
// we do not need to judge according to fromToken.
if (UniversalERC20.isETH(IERC20(fromToken))) {
IWETH(_WETH).deposit{
value: _baseRequest.fromTokenAmount
}();
require(_bytes32ToAddress(batches[0][0].fromToken) == _WETH, "firstToken mismatch");
payer = address(this);
} else {
require(_bytes32ToAddress(batches[0][0].fromToken) == fromToken, "firstToken mismatch");
}
// 2. check total batch amount
{
// avoid stack too deep
uint256 totalBatchAmount;
for (uint256 i = 0; i < batchesAmount.length; ) {
totalBatchAmount += batchesAmount[i];
unchecked {
++i;
}
}
require(
totalBatchAmount <= _baseRequest.fromTokenAmount,
"Route: number of batches should be <= fromTokenAmount"
);
}
// 4. execute batch
// check length, fix DRW-02: LACK OF LENGTH CHECK ON BATATCHES
require(batchesAmount.length == batches.length, "length mismatch");
for (uint256 i = 0; i < batches.length; ) {
if (i > 0) {
require(batches[i][0].fromToken == batches[0][0].fromToken, "Inconsistent fromToken across batches");
}
// execute hop, if the whole swap replacing by pmm fails, the funds will return to dexRouter
_exeHop(
payer,
refundTo,
receiver,
IERC20(_baseRequest.toToken).isETH(),
batchesAmount[i],
batches[i]
);
unchecked {
++i;
}
}
// 5. transfer tokens to user
_transferTokenToUser(_baseRequest.toToken, receiver);
}
//-------------------------------
//------- Users Functions -------
//-------------------------------
/// @notice Executes a smart swap based on the given order ID, supporting complex multi-path swaps. For smartSwap, if fromToken or toToken is ETH, the address needs to be 0xEeee.
/// @param orderId The unique identifier for the swap order, facilitating tracking and reference.
/// @param baseRequest Struct containing the base parameters for the swap, including the source and destination tokens, amount, minimum return, and deadline.
/// @param batchesAmount An array specifying the amount to be swapped in each batch, allowing for split operations.
/// @param batches An array of RouterPath structs defining the routing paths for each batch, enabling swaps through multiple protocols or liquidity pools.
/// @return returnAmount The total amount of destination tokens received from executing the swap.
/// @dev This function orchestrates a swap operation that may involve multiple steps, routes, or protocols based on the provided parameters.
/// It's designed to ensure flexibility and efficiency in finding the best swap paths.
function smartSwapByOrderId(
uint256 orderId,
BaseRequest calldata baseRequest,
uint256[] calldata batchesAmount,
RouterPath[][] calldata batches,
PMMLib.PMMSwapRequest[] calldata // extraData
)
external
payable
isExpired(baseRequest.deadLine)
returns (uint256 returnAmount)
{
emit SwapOrderId(orderId);
return
_smartSwapTo(
msg.sender,
msg.sender,
msg.sender,
baseRequest,
batchesAmount,
batches
);
}
/// @notice Executes a token swap using the Unxswap protocol based on a specified order ID.
/// @param srcToken The source token involved in the swap.
/// @param amount The amount of the source token to be swapped.
/// @param minReturn The minimum amount of tokens expected to be received to ensure the swap does not proceed under unfavorable conditions.
/// @param pools An array of pool identifiers specifying the pools to use for the swap, allowing for optimized routing.
/// @return returnAmount The amount of destination tokens received from the swap.
/// @dev This function allows users to perform token swaps based on predefined orders, leveraging the Unxswap protocol's liquidity pools. It ensures that the swap meets the user's specified minimum return criteria, enhancing trade efficiency and security.
function unxswapByOrderId(
uint256 srcToken,
uint256 amount,
uint256 minReturn,
// solhint-disable-next-line no-unused-vars
bytes32[] calldata pools
) external payable returns (uint256 returnAmount) {
return unxswapTo(
srcToken,
amount,
minReturn,
msg.sender,
pools
);
}
/// @notice Executes a swap tailored for investment purposes, adjusting swap amounts based on the contract's balance. For smartSwap, if fromToken or toToken is ETH, the address needs to be 0xEeee.
/// @param baseRequest Struct containing essential swap parameters like source and destination tokens, amounts, and deadline.
/// @param batchesAmount Array indicating how much of the source token to swap in each batch, facilitating diversified investments.
/// @param batches Detailed routing information for executing the swap across different paths or protocols.
/// @param extraData Additional data for swaps, supporting protocol-specific requirements.
/// @param to The address where the swapped tokens will be sent, typically an investment contract or pool.
/// @return returnAmount The total amount of destination tokens received, ready for investment.
/// @dev This function is designed for scenarios where investments are made in batches or through complex paths to optimize returns. Adjustments are made based on the contract's current token balance to ensure precise allocation.
function smartSwapByInvest( // change function name
BaseRequest memory baseRequest,
uint256[] memory batchesAmount,
RouterPath[][] memory batches,
PMMLib.PMMSwapRequest[] memory extraData,
address to
) external payable returns (uint256 returnAmount) {
return
smartSwapByInvestWithRefund(
baseRequest,
batchesAmount,
batches,
extraData,
to,
to
);
}
function smartSwapByInvestWithRefund(
BaseRequest memory baseRequest,
uint256[] memory batchesAmount,
RouterPath[][] memory batches,
PMMLib.PMMSwapRequest[] memory, // extraData
address to,
address refundTo
)
public
payable
isExpired(baseRequest.deadLine)
returns (uint256 returnAmount)
{
address fromToken = _bytes32ToAddress(baseRequest.fromToken);
require(fromToken != _ETH, "Invalid source token");
require(refundTo != address(0), "refundTo is address(0)");
require(to != address(0), "to is address(0)");
require(baseRequest.fromTokenAmount > 0, "fromTokenAmount is 0");
uint256 amount = IERC20(fromToken).balanceOf(address(this));
for (uint256 i = 0; i < batchesAmount.length; ) {
batchesAmount[i] =
(batchesAmount[i] * amount) /
baseRequest.fromTokenAmount;
unchecked {
++i;
}
}
baseRequest.fromTokenAmount = amount;
returnAmount = _getBalanceOf(baseRequest.toToken, to);
_smartSwapInternal(
baseRequest,
batchesAmount,
batches,
address(this), // payer
refundTo, // refundTo
to // receiver
);
// check minReturnAmount
returnAmount =
_getBalanceOf(baseRequest.toToken, to) -
returnAmount;
require(
returnAmount >= baseRequest.minReturnAmount,
"Min return not reached"
);
emit OrderRecord(
fromToken,
baseRequest.toToken,
tx.origin,
baseRequest.fromTokenAmount,
returnAmount
);
}
/// @notice Executes a swap using the Uniswap V3 protocol.
/// @param receiver The address that will receive the swap funds.
/// @param amount The amount of the source token to be swapped.
/// @param minReturn The minimum acceptable amount of tokens to receive from the swap, guarding against excessive slippage.
/// @param pools An array of pool identifiers used to define the swap route within Uniswap V3.
/// @return returnAmount The amount of tokens received after the completion of the swap.
/// @dev This function wraps and unwraps ETH as required, ensuring the transaction only accepts non-zero `msg.value` for ETH swaps. It invokes `_uniswapV3Swap` to execute the actual swap and handles commission post-swap.
function uniswapV3SwapTo(
uint256 receiver,
uint256 amount,
uint256 minReturn,
uint256[] calldata pools
) external payable returns (uint256 returnAmount) {
emit SwapOrderId((receiver & _ORDER_ID_MASK) >> 160);
(address srcToken, address toToken) = _getUniswapV3TokenInfo(msg.value > 0, pools);
return
_uniswapV3SwapTo(
msg.sender,
receiver,
srcToken,
toToken,
amount,
minReturn,
pools
);
}
/// @notice If srcToken or toToken is ETH, the address needs to be 0xEeee. And for commission validation, ETH needs to be 0xEeee.
function _uniswapV3SwapTo(
address payer,
uint256 receiver,
address srcToken,
address toToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata pools
) internal returns (uint256 returnAmount) {
address receiverAddr = (receiver & _ADDRESS_MASK) == 0 ? msg.sender : _bytes32ToAddress(receiver);
(CommissionInfo memory commissionInfo, TrimInfo memory trimInfo) = _getCommissionAndTrimInfo();
// add permit2
_validateCommissionInfo(commissionInfo, srcToken, toToken, _MODE_LEGACY);
returnAmount = _getBalanceOf(toToken, receiverAddr);
_doUniswapV3Swap(
payer,
receiverAddr,
amount,
minReturn,
toToken,
pools,
commissionInfo,
trimInfo
);
// check minReturnAmount
returnAmount = _getBalanceOf(toToken, receiverAddr) - returnAmount;
require(
returnAmount >= minReturn,
"Min return not reached"
);
emit OrderRecord(
srcToken,
toToken,
tx.origin,
amount,
returnAmount
);
}
function _doUniswapV3Swap(
address payer,
address receiver,
uint256 amount,
uint256 minReturn,
address toToken,
uint256[] calldata pools,
CommissionInfo memory commissionInfo,
TrimInfo memory trimInfo
) private {
(
address middleReceiver,
uint256 balanceBefore
) = _doCommissionFromToken(
commissionInfo,
payer,
receiver,
amount,
trimInfo.hasTrim,
toToken
);
_uniswapV3Swap(
payer,
payable(middleReceiver),
amount,
minReturn,
pools
);
_doCommissionAndTrimToToken(
commissionInfo,
receiver,
balanceBefore,
toToken,
trimInfo
);
}
/// @notice Executes a smart swap directly to a specified receiver address.
/// @param orderId Unique identifier for the swap order, facilitating tracking.
/// @param receiver Address to receive the output tokens from the swap.
/// @param baseRequest Contains essential parameters for the swap such as source and destination tokens, amounts, and deadline.
/// @param batchesAmount Array indicating amounts for each batch in the swap, allowing for split operations.
/// @param batches Detailed routing information for executing the swap across different paths or protocols.
/// @return returnAmount The total amount of destination tokens received from the swap.
/// @dev This function enables users to perform token swaps with complex routing directly to a specified address,
/// optimizing for best returns and accommodating specific trading strategies.
function smartSwapTo(
uint256 orderId,
address receiver,
BaseRequest calldata baseRequest,
uint256[] calldata batchesAmount,
RouterPath[][] calldata batches,
PMMLib.PMMSwapRequest[] calldata // extraData
)
external
payable
isExpired(baseRequest.deadLine)
returns (uint256 returnAmount)
{
emit SwapOrderId(orderId);
return
_smartSwapTo(
msg.sender,
msg.sender,
receiver,
baseRequest,
batchesAmount,
batches
);
}
/// @notice If fromToken or toToken is ETH, the address needs to be 0xEeee. And for commission validation, ETH needs to be 0xEeee.
function _smartSwapTo(
address payer,
address refundTo,
address receiver,
BaseRequest memory baseRequest,
uint256[] memory batchesAmount,
RouterPath[][] memory batches
) internal returns (uint256 returnAmount) {
receiver = receiver == address(0) ? msg.sender : receiver;
(CommissionInfo memory commissionInfo, TrimInfo memory trimInfo) = _getCommissionAndTrimInfo();
uint256 mode = batches[0][0].fromToken & _TRANSFER_MODE_MASK;
_validateCommissionInfo(commissionInfo, _bytes32ToAddress(baseRequest.fromToken), baseRequest.toToken, mode);
returnAmount = _getBalanceOf(baseRequest.toToken, receiver);
{
(
address middleReceiver,
uint256 balanceBefore
) = _doCommissionFromToken(
commissionInfo,
payer,
receiver,
baseRequest.fromTokenAmount,
trimInfo.hasTrim,
baseRequest.toToken
);
_smartSwapInternal(
baseRequest,
batchesAmount,
batches,
payer,
refundTo,
middleReceiver
);
_doCommissionAndTrimToToken(
commissionInfo,
receiver,
balanceBefore,
baseRequest.toToken,
trimInfo
);
}
// check minReturnAmount
returnAmount =
_getBalanceOf(baseRequest.toToken, receiver) -
returnAmount;
require(
returnAmount >= baseRequest.minReturnAmount,
"Min return not reached"
);
emit OrderRecord(
_bytes32ToAddress(baseRequest.fromToken),
baseRequest.toToken,
tx.origin,
baseRequest.fromTokenAmount,
returnAmount
);
}
/// @notice Executes a token swap using the Unxswap protocol, sending the output directly to a specified receiver.
/// The srcToken can be 0xEeee or address(0) for temporary use, the address(0) usage will removed in the future.
/// @param srcToken The source token to be swapped.
/// @param amount The amount of the source token to be swapped.
/// @param minReturn The minimum amount of destination tokens expected from the swap, ensuring the trade does not proceed under unfavorable conditions.
/// @param receiver The address where the swapped tokens will be sent.
/// @param pools An array of pool identifiers to specify the swap route, optimizing for best rates.
/// @return returnAmount The total amount of destination tokens received from the swap.
/// @dev This function facilitates direct swaps using Unxswap, allowing users to specify custom swap routes and ensuring that the output is sent to a predetermined address. It is designed for scenarios where the user wants to directly receive the tokens in their wallet or another contract.
function unxswapTo(
uint256 srcToken,
uint256 amount,
uint256 minReturn,
address receiver,
// solhint-disable-next-line no-unused-vars
bytes32[] calldata pools
) public payable returns (uint256 returnAmount) {
emit SwapOrderId((srcToken & _ORDER_ID_MASK) >> 160);
// validate token info
(address fromToken, address toToken) = _getUnxswapTokenInfo(msg.value > 0, pools);
address srcTokenAddr = _bytes32ToAddress(srcToken);
srcTokenAddr = srcTokenAddr == address(0) ? _ETH : srcTokenAddr;
require(
srcTokenAddr == fromToken,
"unxswap: token mismatch"
);
return
_unxswapTo(
fromToken,
toToken,
amount,
minReturn,
msg.sender,
receiver,
pools
);
}
/// @notice If srcToken is ETH, srcToken needs to be 0xEeee for commission validation and _unxswapInternal.
function _unxswapTo(
address srcToken,
address toToken,
uint256 amount,
uint256 minReturn,
address payer,
address receiver,
// solhint-disable-next-line no-unused-vars
bytes32[] calldata pools
) internal returns (uint256 returnAmount) {
receiver = receiver == address(0) ? msg.sender : receiver;
(CommissionInfo memory commissionInfo, TrimInfo memory trimInfo) = _getCommissionAndTrimInfo();
_validateCommissionInfo(commissionInfo, srcToken, toToken, _MODE_LEGACY);
returnAmount = _getBalanceOf(toToken, receiver);
_doUnxswap(payer, receiver, srcToken, toToken, amount, minReturn, pools, commissionInfo, trimInfo);
// check minReturnAmount
returnAmount = _getBalanceOf(toToken, receiver) - returnAmount;
require(
returnAmount >= minReturn,
"Min return not reached"
);
emit OrderRecord(
srcToken,
toToken,
tx.origin,
amount,
returnAmount
);
return returnAmount;
}
function _doUnxswap(
address payer,
address receiver,
address srcToken,
address toToken,
uint256 amount,
uint256 minReturn,
bytes32[] calldata pools,
CommissionInfo memory commissionInfo,
TrimInfo memory trimInfo
) private {
(
address middleReceiver,
uint256 balanceBefore
) = _doCommissionFromToken(
commissionInfo,
payer,
receiver,
amount,
trimInfo.hasTrim,
toToken
);
address _payer = payer;
_unxswapInternal(
IERC20(srcToken),
amount,
minReturn,
pools,
_payer,
middleReceiver
);
_doCommissionAndTrimToToken(
commissionInfo,
receiver,
balanceBefore,
toToken,
trimInfo
);
}
/// @notice Executes a Uniswap V3 token swap to a specified receiver using structured base request parameters. For uniswapV3, if fromToken or toToken is ETH, the address needs to be 0xEeee.
/// @param orderId Unique identifier for the swap order, facilitating tracking and reference.
/// @param receiver The address that will receive the swapped tokens.
/// @param baseRequest Struct containing essential swap parameters including source token, destination token, amount, minimum return, and deadline.
/// @param pools An array of pool identifiers defining the Uniswap V3 swap route, with encoded swap direction and unwrap flags.
/// @return returnAmount The total amount of destination tokens received from the swap.
/// @dev This function validates token compatibility with the provided pool route and ensures proper swap execution.
/// It supports both ETH and ERC20 token swaps, with automatic WETH wrapping/unwrapping as needed.
/// The function verifies that fromToken matches the first pool and toToken matches the last pool in the route.
function uniswapV3SwapToWithBaseRequest(
uint256 orderId,
address receiver,
BaseRequest calldata baseRequest,
uint256[] calldata pools
)
external
payable
isExpired(baseRequest.deadLine)
returns (uint256 returnAmount)
{
emit SwapOrderId(orderId);
(address srcToken, address toToken) = _getUniswapV3TokenInfo(msg.value > 0, pools);
// validate fromToken and toToken from baseRequest
require(
_bytes32ToAddress(baseRequest.fromToken) == srcToken && baseRequest.toToken == toToken,
"uniswapV3: token mismatch"
);
return
_uniswapV3SwapTo(
msg.sender,
uint256(uint160(receiver)),
srcToken,
toToken,
baseRequest.fromTokenAmount,
baseRequest.minReturnAmount,
pools
);
}
/// @notice Executes a Unxswap token swap to a specified receiver using structured base request parameters. For unxswap, if fromToken or toToken is ETH, the address can be 0xEeee or address(0) for temporary use, the address(0) usage will removed in the future.
/// @param orderId Unique identifier for the swap order, facilitating tracking and reference.
/// @param receiver The address that will receive the swapped tokens.
/// @param baseRequest Struct containing essential swap parameters including source token, destination token, amount, minimum return, and deadline.
/// @param pools An array of pool identifiers defining the Unxswap route, with encoded swap direction and WETH unwrap flags.
/// @return returnAmount The total amount of destination tokens received from the swap.
/// @dev This function validates token compatibility with the provided pool route and ensures proper swap execution.
/// It supports both ETH and ERC20 token swaps, with automatic WETH wrapping/unwrapping as needed.
/// The function verifies that toToken matches the expected output token from the last pool in the route.
function unxswapToWithBaseRequest(
uint256 orderId,
address receiver,
BaseRequest calldata baseRequest,
bytes32[] calldata pools
)
external
payable
isExpired(baseRequest.deadLine)
returns (uint256 returnAmount)
{
emit SwapOrderId(orderId);
(address fromToken, address toToken) = _getUnxswapTokenInfo(msg.value > 0, pools);
// validate fromToken and toToken from baseRequest
address fromTokenAddr = _bytes32ToAddress(baseRequest.fromToken);
require((fromTokenAddr == fromToken) || (fromTokenAddr == address(0) && fromToken == _ETH), "unxswap: fromToken mismatch");
require((baseRequest.toToken == toToken) || (baseRequest.toToken == address(0) && toToken == _ETH), "unxswap: toToken mismatch");
return
_unxswapTo(
fromToken,
toToken,
baseRequest.fromTokenAmount,
baseRequest.minReturnAmount,
msg.sender,
receiver,
pools
);
}
/// @notice For commission validation, ETH needs to be 0xEeee.
function _swapWrap(
uint256 orderId,
address receiver,
bool reversed,
uint256 amount
) internal {
emit SwapOrderId(orderId);
require(amount > 0, "amount must be > 0");
receiver = receiver == address(0) ? msg.sender : receiver;
(CommissionInfo memory commissionInfo, TrimInfo memory trimInfo) = _getCommissionAndTrimInfo();
address srcToken = reversed ? _WETH : _ETH;
address toToken = reversed ? _ETH : _WETH;
_validateCommissionInfo(commissionInfo, srcToken, toToken, _MODE_LEGACY);
(
address middleReceiver,
uint256 balanceBefore
) = _doCommissionFromToken(
commissionInfo,
msg.sender,
receiver,
amount,
trimInfo.hasTrim,
toToken
);
if (reversed) {
IApproveProxy(_APPROVE_PROXY).claimTokens(
_WETH,
msg.sender,
_WNATIVE_RELAY,
amount
);
IWNativeRelayer(_WNATIVE_RELAY).withdraw(amount);
if (middleReceiver != address(this)) {
(bool success, ) = payable(middleReceiver).call{
value: address(this).balance
}("");
require(success, "transfer native token failed");
}
} else {
if (!commissionInfo.isFromTokenCommission) {
require(msg.value == amount, "value not equal amount");
}
IWETH(_WETH).deposit{value: amount}();
if (middleReceiver != address(this)) {
SafeERC20.safeTransfer(IERC20(_WETH), middleReceiver, amount);
}
}
// emit return amount should be the amount after commission
uint256 toTokenCommissionAndTrimAmount = _doCommissionAndTrimToToken(
commissionInfo,
receiver,
balanceBefore,
toToken,
trimInfo
);
emit OrderRecord(
srcToken,
toToken,
tx.origin,
amount,
amount - toTokenCommissionAndTrimAmount
);
}
/// @notice Executes a simple swap between ETH and WETH using encoded parameters.
/// @param orderId Unique identifier for the swap order, facilitating tracking and reference.
/// @param rawdata Encoded data containing swap direction and amount information using bit masks.
/// @dev This function supports bidirectional swaps between ETH and WETH with minimal gas overhead.
/// The rawdata parameter encodes both the direction (reversed flag) and amount using bit operations.
/// When reversed=false: ETH -> WETH, when reversed=true: WETH -> ETH.
function swapWrap(uint256 orderId, uint256 rawdata) external payable {
bool reversed;
uint128 amount;
assembly {
reversed := and(rawdata, _REVERSE_MASK)
amount := and(rawdata, SWAP_AMOUNT)
}
_swapWrap(orderId, msg.sender, reversed, amount);
}
/// @notice Executes a swap between ETH and WETH using structured base request parameters to a specified receiver.
/// @param orderId Unique identifier for the swap order, facilitating tracking and reference.
/// @param receiver The address that will receive the swapped tokens.
/// @param baseRequest Struct containing essential swap parameters including source token, destination token, amount, minimum return, and deadline.
/// @dev This function validates that the token pair is either ETH->WETH or WETH->ETH and executes the swap accordingly.
/// It extracts the amount from the baseRequest and determines the swap direction based on the token addresses.
function swapWrapToWithBaseRequest(
uint256 orderId,
address receiver,
BaseRequest calldata baseRequest
)
external
payable
isExpired(baseRequest.deadLine)
{
bool reversed;
address fromTokenAddr = _bytes32ToAddress(baseRequest.fromToken);
if (fromTokenAddr == _ETH && baseRequest.toToken == _WETH) {
reversed = false;
} else if (fromTokenAddr == _WETH && baseRequest.toToken == _ETH) {
reversed = true;
} else {
revert("SwapWrap: invalid token pair");
}
_swapWrap(orderId, receiver, reversed, baseRequest.fromTokenAmount);
}
function dagSwapByOrderId(
uint256 orderId,
BaseRequest calldata baseRequest,
RouterPath[] calldata paths
) external payable returns (uint256 returnAmount) {
return dagSwapTo(orderId, msg.sender, baseRequest, paths);
}
/// @notice Executes a DAG swap to a specified receiver using structured base request parameters.
/// @param orderId Unique identifier for the swap order, facilitating tracking and reference.
/// @param receiver The address that will receive the swapped tokens.
/// @param baseRequest Struct containing essential swap parameters including source token, destination token, amount, minimum return, and deadline.
/// @param paths An array of RouterPath structs defining the DAG swap route.
/// @return returnAmount The total amount of destination tokens received from the swap.
/// @dev This function validates token compatibility with the provided pool route and ensures proper swap execution.
function dagSwapTo(
uint256 orderId,
address receiver,
BaseRequest calldata baseRequest,
RouterPath[] calldata paths
)
public
payable
isExpired(baseRequest.deadLine)
returns (uint256 returnAmount)
{
require(paths.length > 0, "paths must be > 0");
emit SwapOrderId(orderId);
receiver = receiver == address(0) ? msg.sender : receiver;
(CommissionInfo memory commissionInfo, TrimInfo memory trimInfo) = _getCommissionAndTrimInfo();
uint256 mode = paths[0].fromToken & _TRANSFER_MODE_MASK;
_validateCommissionInfo(commissionInfo, _bytes32ToAddress(baseRequest.fromToken), baseRequest.toToken, mode);
returnAmount = _getBalanceOf(baseRequest.toToken, receiver);
(
address middleReceiver,
uint256 balanceBefore
) = _doCommissionFromToken(
commissionInfo,
msg.sender,
receiver,
baseRequest.fromTokenAmount,
trimInfo.hasTrim,
baseRequest.toToken
);
_dagSwapInternal(
baseRequest,
paths,
msg.sender,
msg.sender,
middleReceiver
);
_doCommissionAndTrimToToken(
commissionInfo,
receiver,
balanceBefore,
baseRequest.toToken,
trimInfo
);
// check minReturnAmount
returnAmount =
_getBalanceOf(baseRequest.toToken, receiver) -
returnAmount;
require(
returnAmount >= baseRequest.minReturnAmount,
"Min return not reached"
);
emit OrderRecord(
_bytes32ToAddress(baseRequest.fromToken),
baseRequest.toToken,
tx.origin,
baseRequest.fromTokenAmount,
returnAmount
);
}
}"
},
"contracts/8/interfaces/AbstractCommissionLib.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Abstract base contract with virtual functions
abstract contract AbstractCommissionLib {
struct CommissionInfo {
bool isFromTokenCommission; //0x00
bool isToTokenCommission; //0x20
uint256 commissionRate; //0x40
address refererAddress; //0x60
address token; //0x80
uint256 commissionRate2; //0xa0
address refererAddress2; //0xc0
bool isToBCommission; //0xe0
}
struct TrimInfo {
bool hasTrim; // 0x00
uint256 trimRate; // 0x20
address trimAddress; // 0x40
uint256 expectAmountOut; // 0x60
uint256 chargeRate; // 0x80
address chargeAddress; // 0xa0
}
function _getCommissionAndTrimInfo()
internal
virtual
returns (CommissionInfo memory commissionInfo, TrimInfo memory trimInfo);
// function _getBalanceOf(address token, address user)
// internal
// virtual
// returns (uint256);
function _doCommissionFromToken(
CommissionInfo memory commissionInfo,
address payer,
address receiver,
uint256 inputAmount,
bool hasTrim,
address toToken
) internal virtual returns (address, uint256);
function _doCommissionAndTrimToToken(
CommissionInfo memory commissionInfo,
address receiver,
uint256 balanceBefore,
address toToken,
TrimInfo memory trimInfo
) internal virtual returns (uint256);
function _validateCommissionInfo(
CommissionInfo memory commissionInfo,
address fromToken,
address toToken,
uint256 mode
) internal pure virtual;
}
"
},
"contracts/8/interfaces/IAdapter.sol": {
"content": "/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
interface IAdapter {
function sellBase(
address to,
address pool,
bytes memory data
) external;
function sellQuote(
address to,
address pool,
bytes memory data
) external;
}
"
},
"contracts/8/interfaces/IApproveProxy.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IApproveProxy {
function isAllowedProxy(address _proxy) external view returns (bool);
function claimTokens(
address token,
address who,
address dest,
uint256 amount
) external;
function tokenApprove() external view returns (address);
function addProxy(address) external;
}
"
},
"contracts/8/interfaces/IDaiLikePermit.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Interface for DAI-style permits
interface IDaiLikePermit {
function permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
"
},
"contracts/8/interfaces/IDexRouter.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity >=0.8.17;
interface IDexRouter {
struct BaseRequest {
uint256 fromToken;
address toToken;
uint256 fromTokenAmount;
uint256 minReturnAmount;
uint256 deadLine;
}
struct RouterPath {
address[] mixAdapters;
address[] assetTo;
uint256[] rawData;
bytes[] extraData;
uint256 fromToken;
}
event OrderRecord(
address fromToken,
address toToken,
address sender,
uint256 fromAmount,
uint256 returnAmount
);
event SwapOrderId(uint256 id);
}"
},
"contracts/8/interfaces/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC20 {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
"
},
"contracts/8/interfaces/IERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT
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);
}
"
},
"contracts/8/interfaces/IUni.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
interface IUni {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function token0() external view returns (address);
function token1() external view returns (address);
function sync() external;
}
"
},
"contracts/8/interfaces/IUniswapV3SwapCallback.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
"
},
"contracts/8/interfaces/IUniV3.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
interface IUniV3 {
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
function token0() external view returns (address);
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
}
"
},
"contracts/8/interfaces/IWETH.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
interface IWETH {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 wad
) external returns (bool);
function deposit() external payable;
function withdraw(uint256 wad) external;
}
"
},
"contracts/8/interfaces/IWNativeRelayer.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
interface IWNativeRelayer {
function withdraw(uint256 _amount) external;
}
"
},
"contracts/8/libraries/Address.sol": {
"content": "/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account)
internal
pure
returns (address payable)
{
return payable(account);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
}
"
},
"contracts/8/libraries/CommissionLib.sol": {
"content": "/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./CommonUtils.sol";
import "../interfaces/AbstractCommissionLib.sol";
/// @title Base contract with common permit handling logics
abstract contract CommissionLib is AbstractCommissionLib, CommonUtils {
uint256 internal constant _COMMISSION_RATE_MASK =
0x000000000000ffffffffffff0000000000000000000000000000000000000000;
uint256 internal constant _COMMISSION_FLAG_MASK =
0xffffffffffff0000000000000000000000000000000000000000000000000000;
uint256 internal constant FROM_TOKEN_COMMISSION =
0x3ca20afc2aaa0000000000000000000000000000000000000000000000000000;
uint256 internal constant TO_TOKEN_COMMISSION =
0x3ca20afc2bbb0000000000000000000000000000000000000000000000000000;
uint256 internal constant FROM_TOKEN_COMMISSION_DUAL =
0x22220afc2aaa0000000000000000000000000000000000000000000000000000;
uint256 internal constant TO_TOKEN_COMMISSION_DUAL =
0x22220afc2bbb0000000000000000000000000000000000000000000000000000;
uint256 internal constant _TO_B_COMMISSION_MASK =
0x8000000000000000000000000000000000000000000000000000000000000000;
uint256 internal constant _TRIM_FLAG_MASK =
0xffffffffffff0000000000000000000000000000000000000000000000000000;
uint256 internal constant _TRIM_EXPECT_AMOUNT_OUT_OR_ADDRESS_MASK =
0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff;
uint256 internal constant _TRIM_RATE_MASK =
0x000000000000ffffffffffff0000000000000000000000000000000000000000;
uint256 internal constant TRIM_FLAG =
0x7777777711110000000000000000000000000000000000000000000000000000;
uint256 internal constant TRIM_DUAL_FLAG =
0x7777777722220000000000000000000000000000000000000000000000000000;
event CommissionAndTrimInfo(
uint256 commissionRate1,
uint256 commissionRate2,
bool isToBCommission,
uint256 trimRate,
uint256 chargeRate
);
// @notice CommissionFromTokenRecord is emitted in assembly, commentted out for contract size saving
// event CommissionFromTokenRecord(
// address fromTokenAddress,
// uint256 commissionAmount,
// address referrerAddress
// );
// @notice CommissionToTokenRecord is emitted in assembly, commentted out for contract size saving
// event CommissionToTokenRecord(
// address toTokenAddress,
// uint256 commissionAmount,
// address referrerAddress
// );
// @notice PositiveSlippageTrimRecord is emitted in assembly, commentted out for contract size saving
// event PositiveSlippageTrimRecord(
// address toTokenAddress,
// uint256 trimAmount,
// address trimAddress
// );
// @notice PositiveSlippageChargeRecord is emitted in assembly, commentted out for contract size saving
// event PositiveSlippageChargeRecord(
// address toTokenAddress,
// uint256 chargeAmount,
// address chargeAddress
// );
// set default value can change when need.
uint256 internal constant commissionRateLimit = 30000000;
uint256 internal constant DENOMINATOR = 10 ** 9;
uint256 internal constant WAD = 1 ether;
uint256 internal constant TRIM_RATE_LIMIT = 100;
uint256 internal constant TRIM_DENOMINATOR = 1000;
function _getCommissionAndTrimInfo()
internal
override
returns (CommissionInfo memory commissionInfo, TrimInfo memory trimInfo)
{
assembly ("memory-safe") {
// let freePtr := mload(0x40)
// mstore(0x40, add(freePtr, 0x100))
let commissionData := calldataload(sub(calldatasize(), 0x20))
let flag := and(commissionData, _COMMISSION_FLAG_MASK)
let isDualreferrers := or(
eq(flag, FROM_TOKEN_COMMISSION_DUAL),
eq(flag, TO_TOK
Submitted on: 2025-10-25 15:06:42
Comments
Log in to comment.
No comments yet.