Проверенный контрактТочноеGPL-2.0-or-later
Aggregator
Адрес0xe047739775bf20485d0ebaa0a033aae3ebd6bda1
- Баланс
0 ETH
- Транзакций
1
- Компилятор
solc 0.8.26
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.26+commit.8a97fa7a
- Язык
- solidity
- Оптимизация
- Да, 2 000 прогонов
- Версия EVM
- cancun
- Через IR
- да
- Лицензия
- GPL-2.0-or-later
- Совпадение
- Точноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 482 161
- Транзакция создания
- 0x2e94a9b37c…2ca6781936
105 файлов
Исходный код большой: показывается один файл. Выберите файл в списке.
- src/Aggregator.solглавный67,89 КБ
- lib/infinity-periphery/lib/infinity-core/lib/solmate/src/tokens/ERC20.sol6,81 КБ
- lib/infinity-periphery/lib/infinity-core/lib/solmate/src/utils/SafeTransferLib.sol6,34 КБ
- lib/infinity-periphery/lib/infinity-core/src/Vault.sol8,76 КБ
- lib/infinity-periphery/lib/infinity-core/src/VaultToken.sol4,43 КБ
- lib/infinity-periphery/lib/infinity-core/src/interfaces/IERC20Minimal.sol3,04 КБ
- lib/infinity-periphery/lib/infinity-core/src/interfaces/IExtsload.sol593 Б
- lib/infinity-periphery/lib/infinity-core/src/interfaces/IHooks.sol151 Б
- lib/infinity-periphery/lib/infinity-core/src/interfaces/ILockCallback.sol465 Б
- lib/infinity-periphery/lib/infinity-core/src/interfaces/IPoolManager.sol1,77 КБ
- lib/infinity-periphery/lib/infinity-core/src/interfaces/IProtocolFeeController.sol836 Б
- lib/infinity-periphery/lib/infinity-core/src/interfaces/IProtocolFees.sol3,08 КБ
- lib/infinity-periphery/lib/infinity-core/src/interfaces/IVault.sol6,51 КБ
- lib/infinity-periphery/lib/infinity-core/src/interfaces/IVaultToken.sol2,92 КБ
- lib/infinity-periphery/lib/infinity-core/src/libraries/CustomRevert.sol2,36 КБ
- lib/infinity-periphery/lib/infinity-core/src/libraries/LPFeeLibrary.sol3,79 КБ
- lib/infinity-periphery/lib/infinity-core/src/libraries/ProtocolFeeLibrary.sol2,88 КБ
- lib/infinity-periphery/lib/infinity-core/src/libraries/SafeCast.sol2,06 КБ
- lib/infinity-periphery/lib/infinity-core/src/libraries/SettlementGuard.sol4,5 КБ
- lib/infinity-periphery/lib/infinity-core/src/libraries/VaultReserve.sol1,76 КБ
- lib/infinity-periphery/lib/infinity-core/src/libraries/math/Encoded.sol3,95 КБ
- lib/infinity-periphery/lib/infinity-core/src/libraries/math/UnsafeMath.sol1,21 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/interfaces/IBinPoolManager.sol10,95 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/libraries/BinHelper.sol14,12 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/libraries/BinPool.sol22,41 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/libraries/BinPoolParametersHelper.sol1,37 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/libraries/BinPosition.sol2,3 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/libraries/Constants.sol640 Б
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/libraries/FeeHelper.sol2,49 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/libraries/PriceHelper.sol2,93 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/libraries/math/BitMath.sol3,97 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/libraries/math/LiquidityConfigurations.sol3,5 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/libraries/math/PackedUint128Math.sol8,92 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/libraries/math/SafeCast.sol9,51 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/libraries/math/TreeMath.sol7,54 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/libraries/math/Uint128x128Math.sol7,72 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/libraries/math/Uint256x256Math.sol10,54 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-bin/types/BinSlot0.sol3,14 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-cl/interfaces/ICLPoolManager.sol9,87 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-cl/libraries/BitMath.sol2,68 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-cl/libraries/CLPool.sol21,5 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-cl/libraries/CLPosition.sol4,85 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-cl/libraries/FixedPoint128.sol344 Б
- lib/infinity-periphery/lib/infinity-core/src/pool-cl/libraries/FixedPoint96.sol413 Б
- lib/infinity-periphery/lib/infinity-core/src/pool-cl/libraries/FullMath.sol5,51 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-cl/libraries/LiquidityMath.sol866 Б
- lib/infinity-periphery/lib/infinity-core/src/pool-cl/libraries/SqrtPriceMath.sol14,17 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-cl/libraries/SwapMath.sol6,74 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-cl/libraries/Tick.sol10,01 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-cl/libraries/TickBitmap.sol6,42 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-cl/libraries/TickMath.sol12,63 КБ
- lib/infinity-periphery/lib/infinity-core/src/pool-cl/types/CLSlot0.sol3,81 КБ
- lib/infinity-periphery/lib/infinity-core/src/types/BalanceDelta.sol2,36 КБ
- lib/infinity-periphery/lib/infinity-core/src/types/Currency.sol5,29 КБ
- lib/infinity-periphery/lib/infinity-core/src/types/PoolId.sol468 Б
- lib/infinity-periphery/lib/infinity-core/src/types/PoolKey.sol1,02 КБ
- lib/infinity-periphery/src/base/ReentrancyLock.sol938 Б
- lib/infinity-periphery/src/interfaces/external/IWETH9.sol409 Б
- lib/openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol3,01 КБ
- lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol4,03 КБ
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol8,91 КБ
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol6,59 КБ
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1,19 КБ
- lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol3,86 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/Ownable.sol3,1 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol1,99 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol880 Б
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol6,72 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol472 Б
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2,78 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Address.sol6,26 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Context.sol963 Б
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol3,93 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Strings.sol3,1 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol7,73 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol3,76 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol15,12 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol1,26 КБ
- lib/v4-core/src/interfaces/IExtsload.sol1,02 КБ
- lib/v4-core/src/interfaces/IExttload.sol699 Б
- lib/v4-core/src/interfaces/IHooks.sol8,3 КБ
- lib/v4-core/src/interfaces/IPoolManager.sol13,45 КБ
- lib/v4-core/src/interfaces/IProtocolFees.sol2,49 КБ
- lib/v4-core/src/interfaces/callback/IUnlockCallback.sol488 Б
- lib/v4-core/src/interfaces/external/IERC20Minimal.sol3,04 КБ
- lib/v4-core/src/interfaces/external/IERC6909Claims.sol3,16 КБ
- lib/v4-core/src/libraries/CustomRevert.sol5,17 КБ
- lib/v4-core/src/libraries/SafeCast.sol2,27 КБ
- lib/v4-core/src/types/BalanceDelta.sol2,34 КБ
- lib/v4-core/src/types/BeforeSwapDelta.sol1,47 КБ
- lib/v4-core/src/types/Currency.sol5,46 КБ
- lib/v4-core/src/types/PoolId.sol539 Б
- lib/v4-core/src/types/PoolKey.sol805 Б
- src/base/ImmutableState.sol3,58 КБ
- src/base/NativeWrapper.sol1,75 КБ
- src/base/PausableOwner.sol921 Б
- src/base/Payment.sol1,97 КБ
- src/interfaces/IAdapter.sol258 Б
- src/interfaces/IAggregator.sol32,73 КБ
- src/interfaces/ISwapExecutor.sol2,15 КБ
- src/interfaces/IUniV3StyledSwapCallback.sol1,39 КБ
- src/libraries/CommonUtils.sol1,18 КБ
- src/libraries/FeeHelper.sol6,03 КБ
- src/libraries/PathAdapterHelper.sol3,08 КБ
- src/libraries/PathRawDataHelper.sol1,71 КБ
src/Aggregator.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.26;
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {ILockCallback} from "infinity-periphery/lib/infinity-core/src/interfaces/ILockCallback.sol";
import {IUnlockCallback} from "uniswap-v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {IWETH9} from "infinity-periphery/src/interfaces/external/IWETH9.sol";
import {FullMath} from "infinity-core/src/pool-cl/libraries/FullMath.sol";
import {ReentrancyLock} from "infinity-periphery/src/base/ReentrancyLock.sol";
import {NativeWrapper} from "./base/NativeWrapper.sol";
import {PausableOwner} from "./base/PausableOwner.sol";
import {FeeHelper} from "./libraries/FeeHelper.sol";
import {IAdapter} from "./interfaces/IAdapter.sol";
import {IUniV3StyledSwapCallback} from "./interfaces/IUniV3StyledSwapCallback.sol";
import {IAggregator} from "./interfaces/IAggregator.sol";
import {ISwapExecutor} from "./interfaces/ISwapExecutor.sol";
import {CommonUtils} from "./libraries/CommonUtils.sol";
import {PathRawDataHelper} from "./libraries/PathRawDataHelper.sol";
import {PathAdapterHelper} from "./libraries/PathAdapterHelper.sol";
import {Payment} from "./base/Payment.sol";
/// @dev UUPS upgradeable: deployed behind an ERC1967 proxy. The formerly-inlined adapters
/// (UniV2/PCSV2, UniV3-styled, Infinity, UniV4) now live in the SwapExecutor contract and are
/// reached via delegatecall — the combined bytecode no longer fits under the EIP-170 limit with
/// the upgradeability machinery included. Because it is delegatecall, everything still executes
/// in this contract's context: traders keep approving the proxy, the swap callbacks still hit
/// the proxy, and route calldata is byte-for-byte compatible with the non-upgradeable version.
///
/// Storage layout rules for future upgrades: the variables declared below occupy slots from 0
/// in declaration order and are APPEND-ONLY — never reorder, retype or delete them. Inherited
/// OZ upgradeable state (Ownable2Step, Pausable, Initializable) lives in ERC-7201 namespaced
/// slots and cannot collide; so does this contract's own signed-swap state
/// (`SwapAuthStorage`, namespace `pancakeswap.storage.AggregatorSwapAuth`), whose struct is
/// append-only in the same way. ReentrancyLock uses transient storage only.
contract Aggregator is IAggregator, Payment, NativeWrapper, PausableOwner, ReentrancyLock, UUPSUpgradeable {
using CommonUtils for *;
using PathRawDataHelper for uint256;
using PathAdapterHelper for uint256;
using FeeHelper for uint256;
/// @notice emit event when a fee is charged
/// @dev Carries only the protocol's share of the fee; a referral partner's share is reported
/// separately by PartnerFeeRecord. Not emitted at all when the protocol share is zero.
event FeeRecord(address indexed token, uint256 feeAmount, address recipient);
/// @notice emit event when a swap order is executed successfully
/// @dev orderId is the caller-supplied id used to track the order. It is indexed so an order can
/// be looked up directly, and it lives here rather than in a separate early event so that a
/// transaction carrying several swaps pairs each id with its own result unambiguously.
event OrderRecord(
uint256 indexed orderId,
address inputToken,
address outputToken,
address sender,
uint256 inputAmount,
uint256 outputAmount,
address recipient
);
/// @notice emit event when an adapter is whitelisted / unwhitelisted
event AdapterWhitelisted(address adapter, bool whitelisted);
/// @notice emit event when the protocol fee receiver address is updated
event FeeReceiverUpdated(address indexed newFeeReceiver);
/// @notice emit event when a referral fee is paid out to a partner
/// @dev feeAmount and surplusAmount are reported separately because the two are scaled by
/// independent rates; the partner receives them as a single transfer of the sum. `token` is
/// the swap's output token, carried here so payouts can be attributed without joining
/// against the OrderRecord of the same transaction.
event PartnerFeeRecord(
uint16 indexed partnerId,
address indexed recipient,
address indexed token,
uint256 feeAmount,
uint256 surplusAmount
);
/// @notice emit event when a partner is registered or updated
event PartnerSet(uint16 indexed partnerId, address indexed recipient, uint16 feeShareBps, uint16 surplusBps);
/// @notice emit event when a swap executed through `swapExactInWithSource` succeeds, recording
/// which entry point the trade was attributed to
/// @dev Emitted after the swap, in the same transaction as the matching OrderRecord. orderId is
/// carried for the same reason as on OrderRecord: a transaction may hold several swaps and
/// the two events are joined on (txHash, orderId). `sender` is the attributed account the
/// backend signed for (defaults to msg.sender when the caller passed address(0)), which for
/// a contract integrator is the trader rather than the integrator. Multiple SourceRecords
/// with the same orderId across transactions indicate a replay (see
/// IAggregator.swapExactInWithSource) and should be deduplicated off-chain.
event SourceRecord(uint256 indexed orderId, address indexed sender, uint32 indexed sourceId);
/// @notice emit event when a source signer is enabled or disabled
event SourceSignerSet(address indexed signer, bool enabled);
/// @notice emit event when an adapter is marked as requiring (or no longer requiring) a signed swap
event AdapterAuthRequiredSet(address indexed adapter, bool required);
/// @notice emit event when a swap-auth signer is enabled or disabled
event SwapAuthSignerSet(address indexed signer, bool enabled);
/// @notice Thrown when the swap executor address passed to the constructor is zero
error ZeroAddress();
/// @notice Thrown when the fallback receives a selector that is not one of the SwapExecutor's
/// swap callbacks
error UnknownCallback(bytes4 selector);
/// @notice The delegatecall target hosting the formerly-inlined adapters and their callbacks.
/// @dev Immutable in the implementation, so swapping the executor requires a UUPS upgrade to a
/// new implementation — deliberately the same authorization path as any other code change.
address public immutable SWAP_EXECUTOR;
/// @notice exteranl adapters are by default not allowed to be used in the aggregator unless whitelisted
mapping(address => bool) public isAdapterWhitelisted;
/// @notice Protocol-level fee receiver: receives all percentage fees and positive price-impact
/// surplus that is not split off to a referral partner. Must be set by the owner before
/// any fee-bearing swap is executed.
address public feeReceiver;
/// @notice Referral partner registry. partnerId 0 is permanently reserved to mean "no partner",
/// so it is never written and always reads as an unregistered entry.
mapping(uint16 => Partner) public partners;
/// @notice Backend keys allowed to sign source attributions for `swapExactInWithSource`.
/// @dev Written only by the owner via batchSetSourceSigners; a single cold SLOAD on the swap
/// path. Appended after `partners` to keep the storage layout upgrade-safe.
mapping(address => bool) public isSourceSigner;
/// @notice State of signed swaps (see IAggregator.swapExactIn, "Signed swaps"), kept in an
/// ERC-7201 namespace instead of the linear layout above. It therefore never collides
/// with variables appended there, and a delegatecall target (e.g. the SwapExecutor) can
/// reach it through the same slot constant without mirroring this contract's layout.
/// @dev New members may only be appended at the end of the struct.
/// @custom:storage-location erc7201:pancakeswap.storage.AggregatorSwapAuth
struct SwapAuthStorage {
/// @dev External adapters that may only run inside a signed swap; set via setAdapterAuthRequired.
mapping(address adapter => bool) isAdapterAuthRequired;
/// @dev Backend keys allowed to sign swap authorizations; set via batchSetSwapAuthSigners.
/// Independent from `isSourceSigner`: source signatures are attribution only and
/// replayable, swap authorizations gate adapters and are single-use.
mapping(address signer => bool) isSwapAuthSigner;
/// @dev Used nonces, Permit2-style unordered bitmap: nonce `n` is bit `n & 0xff` of word `n >> 8`.
mapping(uint256 wordPos => uint256) nonceBitmap;
}
/// @dev keccak256(abi.encode(uint256(keccak256("pancakeswap.storage.AggregatorSwapAuth")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant SWAP_AUTH_STORAGE_LOCATION =
0xc40e46c0639afa3a5928f5e128167d7687a375f3a54cce6f65236844d0651400;
/// @notice EIP-712 type hash of the struct a source signer signs, see IAggregator.swapExactInWithSource
bytes32 public constant SOURCE_TYPEHASH = keccak256("Source(uint32 sourceId,address sender,bytes32 paramsHash)");
/// @notice EIP-712 type hash of the struct a swap-auth signer signs, see IAggregator.swapExactIn
bytes32 public constant SWAP_AUTH_TYPEHASH = keccak256("SwapAuth(bytes32 paramsHash,uint256 nonce)");
bytes32 private constant EIP712_DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 private constant EIP712_NAME_HASH = keccak256("PancakeSwapAggregator");
bytes32 private constant EIP712_VERSION_HASH = keccak256("1");
/// @dev WETH9 and SWAP_EXECUTOR are immutables baked into the implementation's code, which is
/// the standard (and gas-cheapest) way to carry per-chain constants in a UUPS setup.
/// @custom:oz-upgrades-unsafe-allow constructor state-variable-immutable
constructor(IWETH9 _weth9, address _swapExecutor) NativeWrapper(_weth9) {
if (_swapExecutor == address(0)) revert ZeroAddress();
SWAP_EXECUTOR = _swapExecutor;
_disableInitializers();
}
/// @notice Forwarder for the swap callbacks whose implementations live in the SwapExecutor:
/// the PancakeSwap V3 / Uniswap V3-styled (incl. Aerodrome Slipstream) swap callbacks,
/// the Infinity Vault `lockAcquired` and the Uniswap V4 PoolManager `unlockCallback`.
/// Reached via delegatecall so the executor pays pools from this contract's
/// balance/approvals; msg.sender is preserved, so the executor's own guards (transient
/// pool address for V3, `onlyByVault`, `onlyByPoolManager`) apply exactly as when the
/// code was inlined. Any selector outside this whitelist reverts, matching the
/// previous behaviour where unknown calls found no function to land on. Plain ETH
/// transfers are unaffected: they go to NativeWrapper's `receive()`.
/// @dev The selector whitelist is deliberately hardcoded: extending it requires a UUPS
/// upgrade, the same authorization path as changing SWAP_EXECUTOR itself. The executor's
/// return data is already ABI-encoded for the original caller (the pool/vault), so it is
/// bubbled up raw instead of a decode/re-encode round trip.
fallback() external {
bytes4 selector = msg.sig;
if (
selector != IUniV3StyledSwapCallback.pancakeV3SwapCallback.selector
&& selector != IUniV3StyledSwapCallback.uniswapV3SwapCallback.selector
&& selector != ILockCallback.lockAcquired.selector
&& selector != IUnlockCallback.unlockCallback.selector
) {
revert UnknownCallback(selector);
}
bytes memory returnData = _delegateToExecutor(msg.data);
assembly ("memory-safe") {
return(add(returnData, 32), mload(returnData))
}
}
/// @notice Initializes the proxy. Replaces the old constructor's `Ownable(msg.sender)` +
/// `feeReceiver = msg.sender` with explicit parameters, since under a proxy msg.sender
/// would be whatever deployed the proxy rather than the intended operator.
function initialize(address initialOwner, address _feeReceiver) external initializer {
__PausableOwner_init(initialOwner);
__UUPSUpgradeable_init();
if (_feeReceiver == address(0)) revert InvalidFeeReceiver();
feeReceiver = _feeReceiver;
emit FeeReceiverUpdated(_feeReceiver);
}
/// @dev UUPS upgrade authorization — owner only.
function _authorizeUpgrade(address) internal override onlyOwner {}
modifier checkDeadline(uint256 deadline) {
if (block.timestamp > deadline) revert TransactionDeadlinePassed();
_;
}
/// @inheritdoc IAggregator
function swapWrap(uint256 orderId, uint256 amount, bool isWrap, uint256 feeConfig, address recipient)
external
payable
isNotLocked
whenNotPaused
returns (uint256 outputAmtReceived)
{
if (recipient == address(0)) recipient = msg.sender;
if (amount == 0) {
revert ZeroAmount();
}
address inputToken;
address outputToken;
if (isWrap) {
if (msg.value == 0) revert ZeroNativeToken();
if (msg.value != amount) revert AmountMisMatch();
inputToken = CommonUtils.ETH;
outputToken = address(WETH9);
_wrap(amount);
} else {
if (msg.value > 0) revert NonZeroNativeToken();
inputToken = address(WETH9);
outputToken = CommonUtils.ETH;
_transferInternal(msg.sender, address(this), inputToken, amount);
_unwrap(amount);
}
outputAmtReceived = amount;
// swapWrap is a 1:1 conversion; only a percentage fee applies (no price-impact surplus), so
// the fee percentage (bits 255-240) alone decides whether anything is charged.
if ((feeConfig >> 240) != 0) {
uint256 feeAmount = feeConfig.getFeeAmount(outputAmtReceived);
outputAmtReceived -= feeAmount;
_settleFee(outputToken, feeAmount, 0, feeConfig.getPartnerId());
}
_transferInternal(address(this), recipient, outputToken, outputAmtReceived);
emit OrderRecord(orderId, inputToken, outputToken, msg.sender, amount, outputAmtReceived, recipient);
}
/// @inheritdoc IAggregator
function swapExactIn(
uint256 orderId,
BaseExactInRequest calldata request,
uint256[] calldata routesAmount,
RouterPath[][] calldata routes,
uint256 feeConfig,
address recipient
) external payable returns (uint256 outputAmtReceived) {
/// @dev Unspent input from a partially filled hop returns to the caller, which is the exact
/// behaviour this selector had before `refundTo` existed. For an EOA trader that is the
/// trader; for a contract integrator it is the integrator, so integrators swapping on
/// behalf of a user should call `swapExactInWithRefundTo` instead.
return _swapExactIn(orderId, request, routesAmount, routes, feeConfig, recipient, msg.sender, false);
}
/// @inheritdoc IAggregator
function swapExactInWithRefundTo(
uint256 orderId,
BaseExactInRequest calldata request,
uint256[] calldata routesAmount,
RouterPath[][] calldata routes,
uint256 feeConfig,
address recipient,
address refundTo
) external payable returns (uint256 outputAmtReceived) {
return _swapExactIn(
orderId,
request,
routesAmount,
routes,
feeConfig,
recipient,
refundTo == address(0) ? msg.sender : refundTo,
false
);
}
/// @inheritdoc IAggregator
function swapExactInWithSource(
uint256 orderId,
BaseExactInRequest calldata request,
uint256[] calldata routesAmount,
RouterPath[][] calldata routes,
uint256 feeConfig,
address recipient,
address refundTo,
bytes calldata sourceData
) external payable returns (uint256 outputAmtReceived) {
/// @dev Hash the decoded values re-encoded canonically rather than a slice of msg.data: ABI
/// dynamic parameters are located via offsets, so a caller could craft a non-canonical
/// encoding where the hashed bytes match what was signed while the routes actually
/// decoded point elsewhere. abi.encode of the decoded values maps uniquely onto the
/// off-chain abi.encode the backend hashed. Raw recipient / refundTo are hashed, before
/// the address(0) -> msg.sender fallback, so the backend signs exactly what is sent.
(uint32 sourceId, address sender) = _verifySource(
keccak256(abi.encode(orderId, request, routesAmount, routes, feeConfig, recipient, refundTo)), sourceData
);
outputAmtReceived = _swapExactIn(
orderId,
request,
routesAmount,
routes,
feeConfig,
recipient,
refundTo == address(0) ? msg.sender : refundTo,
false
);
emit SourceRecord(orderId, sender, sourceId);
}
/// @inheritdoc IAggregator
function swapExactInPrefunded(
uint256 orderId,
BaseExactInRequest calldata request,
uint256[] calldata routesWeight,
RouterPath[][] calldata routes,
uint256 feeConfig,
address recipient,
address refundTo,
uint256 expectedInputAmount
) external payable returns (uint256 outputAmtReceived) {
return _swapExactInPrefunded(
orderId, request, routesWeight, routes, feeConfig, recipient, refundTo, expectedInputAmount
);
}
/// @inheritdoc IAggregator
function swapExactInPrefundedWithSource(
uint256 orderId,
BaseExactInRequest calldata request,
uint256[] calldata routesWeight,
RouterPath[][] calldata routes,
uint256 feeConfig,
address recipient,
address refundTo,
uint256 expectedInputAmount,
bytes calldata sourceData
) external payable returns (uint256 outputAmtReceived) {
/// @dev Same canonical re-encoding as swapExactInWithSource, prefixed with this function's
/// selector. Without the prefix the two entrypoints would hash identical fields, and a
/// signature issued for weights here would also verify there, where the same numbers
/// are absolute amounts (and vice versa). expectedInputAmount is signed too: it decides
/// how much is swapped and how far the slippage floor and the quoted amount scale down.
(uint32 sourceId, address sender) = _verifySource(
keccak256(
abi.encode(
IAggregator.swapExactInPrefundedWithSource.selector,
orderId,
request,
routesWeight,
routes,
feeConfig,
recipient,
refundTo,
expectedInputAmount
)
),
sourceData
);
outputAmtReceived = _swapExactInPrefunded(
orderId, request, routesWeight, routes, feeConfig, recipient, refundTo, expectedInputAmount
);
emit SourceRecord(orderId, sender, sourceId);
}
/// @notice Decode `sourceData` and check its signature against the enabled source signers.
/// @dev Reverts rather than returning a flag: a source call with a bad signature must not fall
/// through to an unattributed swap, or integrators could never tell the two apart.
/// @param paramsHash keccak256 of the canonically re-encoded swap parameters
/// @param sourceData abi.encode(uint32 sourceId, address sender, bytes signature)
/// @return sourceId The non-zero source identifier that was signed
/// @return sender The attributed account that was signed: the caller-supplied value, or
/// msg.sender when that was address(0)
function _verifySource(bytes32 paramsHash, bytes calldata sourceData)
internal
view
returns (uint32 sourceId, address sender)
{
bytes memory signature;
(sourceId, sender, signature) = abi.decode(sourceData, (uint32, address, bytes));
if (sourceId == 0) revert InvalidSourceId();
if (sender == address(0)) sender = msg.sender;
bytes32 digest = MessageHashUtils.toTypedDataHash(
DOMAIN_SEPARATOR(), keccak256(abi.encode(SOURCE_TYPEHASH, sourceId, sender, paramsHash))
);
// tryRecover rejects malformed lengths and high-s (malleable) signatures with a non-zero error
(address signer, ECDSA.RecoverError err,) = ECDSA.tryRecover(digest, signature);
if (err != ECDSA.RecoverError.NoError || !isSourceSigner[signer]) revert InvalidSourceSignature();
}
/// @notice EIP-712 domain separator for source signatures
/// @dev Rebuilt on every call rather than cached: an immutable would be computed in the
/// implementation's constructor with address(this) == implementation, not the proxy, and
/// storage would need a reinitializer on upgrade. One keccak over five words costs less
/// than the SLOAD a cached value would need, and it follows a chain-id change for free.
function DOMAIN_SEPARATOR() public view returns (bytes32) {
return keccak256(
abi.encode(EIP712_DOMAIN_TYPEHASH, EIP712_NAME_HASH, EIP712_VERSION_HASH, block.chainid, address(this))
);
}
/// @notice Shared implementation behind `swapExactIn`, `swapExactInWithRefundTo`,
/// `swapExactInWithSource`, `swapExactInPrefunded` and `swapExactInPrefundedWithSource`.
/// @dev Without the unreachable self-call at the top, the Yul optimizer inlines this whole body
/// into every external entrypoint that calls it (one copy each, ~3KB apiece at 2000 runs),
/// which is what pushed the implementation against the EIP-170 limit when the third
/// entrypoint was added. The inliner never inlines a function that calls itself, so the
/// dead branch keeps exactly one copy of the body behind a plain internal jump; the
/// condition cannot be proven false at compile time (calldata length) and can never be true
/// at run time (calldata is bounded by gas). It costs one comparison per swap.
/// testAggregator_ByteCodeSize catches it if a future compiler sees through the guard.
/// @param routesAmount The absolute input amount of each route. In memory rather than calldata
/// because the pre-funded entrypoints compute it; the pull-based entrypoints
/// copy theirs in.
/// @param request In memory rather than calldata because the pre-funded entrypoints may scale
/// its minOutputAmount (and the quotedAmount in `feeConfig`) down to the input
/// that arrived, see `_swapExactInPrefunded`; the pull-based entrypoints copy
/// theirs in.
/// @param refundTo Receives the unspent input of a partially filled hop. Already normalised by
/// the calling entrypoint, so it is never address(0).
/// @param prefunded False: an ERC20 input is pulled from msg.sender. True: the input already
/// sits in this contract and nothing is pulled, and the routes of a native
/// input may add up to less than msg.value, see
/// IAggregator.swapExactInPrefunded. A bool rather than a payer
/// address, so no caller can ever name a third party to pull from.
function _swapExactIn(
uint256 orderId,
BaseExactInRequest memory request,
uint256[] memory routesAmount,
RouterPath[][] calldata routes,
uint256 feeConfig,
address recipient,
address refundTo,
bool prefunded
) internal checkDeadline(request.deadline) isNotLocked whenNotPaused returns (uint256 outputAmtReceived) {
// unreachable: see the @dev note above
if (routes.length == type(uint256).max) {
return _swapExactIn(orderId, request, routesAmount, routes, feeConfig, recipient, refundTo, prefunded);
}
/// @dev Signed swap: one extra trailing route carries the authorization, see
/// IAggregator.swapExactIn "Signed swaps". From here on every loop over the executable
/// routes is bounded by `routesAmount.length`, never `routes.length`, so the trailing
/// auth route is never executed.
/// A signed swap needs at least one executable route; `routesAmount = []` with a single
/// route stays the plain length-mismatch error it always was.
/// No `authorized` local: this function is recursive (see above), so via-IR cannot move
/// its variables to memory and it has no stack slot to spare. Once this check passes,
/// "signed" is exactly `routes.length != routesAmount.length`, recomputed where needed.
/// A pre-funded swap arrives here already verified: `_swapExactInPrefunded` checks its
/// authorization over the weights and the unscaled quote, which this function never
/// sees, and only it can set `prefunded`. Its `routesAmount` has one entry per weight,
/// so the same length test identifies it as signed here.
if (routesAmount.length != 0 && routes.length == routesAmount.length + 1) {
if (!prefunded) _verifyPullSwapAuth(orderId, request, routesAmount, routes, feeConfig, recipient);
} else if (routes.length != routesAmount.length) {
revert RoutesLengthNotMatchRoutesAmountLength();
}
if (recipient == address(0)) recipient = msg.sender;
// a pre-funded input already sits in this contract, exactly like a native input does
address payer = prefunded || request.inputToken == CommonUtils.ETH ? address(this) : msg.sender;
uint256 totalInputTokenAmount;
{
if (request.inputToken == CommonUtils.ETH && msg.value == 0) {
revert ZeroNativeToken();
}
if (request.inputToken != CommonUtils.ETH && msg.value > 0) {
revert NonZeroNativeToken();
}
/// @dev make sure inputToken always match the fromToken speicified in the route[*][0]
uint256 amount;
for (uint256 i = 0; i < routesAmount.length; ++i) {
totalInputTokenAmount += routesAmount[i];
if (request.inputToken != routes[i][0].fromToken) {
if (request.inputToken.isETH() && routes[i][0].fromToken == address(WETH9)) {
amount += routesAmount[i];
} else if (request.inputToken == address(WETH9) && routes[i][0].fromToken.isETH()) {
amount += routesAmount[i];
} else {
revert InputTokenNotMatchRouteFromToken();
}
}
}
// a pre-funded swap can trade less than msg.value: what it does not was already refunded,
// see `_swapExactInPrefunded`
if (!prefunded && request.inputToken.isETH() && msg.value != totalInputTokenAmount) {
revert AmountMisMatch();
}
// in case more than one route requires wrap/unwrap, we batch it together
if (amount > 0) {
if (request.inputToken.isETH()) {
_wrap(amount);
} else {
// means inputToken is WETH9 and routes[i].fromToken has .isETH()
// payer is msg.sender here, or this contract when pre-funded, in which case the
// WETH is already in place and the transfer is a no-op
_transferInternal(payer, address(this), request.inputToken, totalInputTokenAmount);
_unwrap(amount);
}
payer = address(this);
}
}
address outputToken = request.outputToken;
// check the output token balance of the recipient before the swap
uint256 initialUserOutputTokenBalance = outputToken.balanceOf(recipient);
/// @dev check if we need to send the output token back to the aggregator contract, this can happen in 2 cases:
/// 1. output token is ETH or WETH (wrap/unwrap might be needed)
/// 2. feeConfig carries a fee percentage or enables surplus capture (quotedAmount above
/// minOutputAmount), which means we may need to charge a fee.
/// A partnerId alone, or a quotedAmount at or below minOutputAmount, charges nothing, so it
/// must not pull the output through this contract: the extra transfer taxes fee-on-transfer
/// tokens twice and breaks tokens that restrict senders.
bool sendOutputBackToAggregator =
(outputToken.isETH() || outputToken == address(WETH9)) || feeConfig.chargesFee(request.minOutputAmount);
/// @notice execute each route in sequence (assume we have several routes)
for (uint256 i = 0; i < routesAmount.length; ++i) {
_execExactInRoute(
payer,
sendOutputBackToAggregator ? address(this) : recipient, // recipient
refundTo, // refundTo: where unspent hop input goes
routesAmount[i], // input token amount
routes[i], // hops
routes.length != routesAmount.length // signed swap: auth-required adapters may run
);
}
/// @dev batch wrap/unwrap output token if necessary
if (outputToken.isETH()) {
_unwrapIfAny();
} else if (outputToken == address(WETH9)) {
_wrapIfAny();
}
if (sendOutputBackToAggregator) {
/// @dev we can assure that all the output token has been sent back to this contract
outputAmtReceived = outputToken.balanceOf(address(this));
if (feeConfig.chargesFee(request.minOutputAmount)) {
// Step 1: Capture positive price-impact surplus.
// quotedAmount is encoded in bits 223-0 of feeConfig.
// Surplus capture is only active when quotedAmount is strictly above the user's
// slippage floor (request.minOutputAmount), ensuring it represents a meaningful
// price-improvement rather than an arbitrary low value. When active and the actual
// swap output exceeds quotedAmount, the difference represents favourable price
// movement between quote time and on-chain execution. We cap the user-visible
// output at quotedAmount; the excess becomes surplus, split in Step 3.
uint256 surplus;
uint256 quotedAmount = feeConfig.getQuotedAmount();
if (quotedAmount > request.minOutputAmount && outputAmtReceived > quotedAmount) {
surplus = outputAmtReceived - quotedAmount;
// Cap user-visible output to what was quoted; the surplus is settled below
outputAmtReceived = quotedAmount;
}
// Step 2: Calculate the percentage-based fee on the (possibly capped) output.
// feePercentage == 0 is permitted for surplus-only mode (no percentage fee charged).
uint256 feeAmount = feeConfig.getFeeAmount(outputAmtReceived);
outputAmtReceived -= feeAmount;
// Step 3: Split the fee between the referral partner named by feeConfig (if any)
// and the protocol feeReceiver, then pay both out. The two fee types are passed
// separately because a partner is configured with an independent rate for each.
_settleFee(outputToken, feeAmount, surplus, feeConfig.getPartnerId());
}
_transferInternal(address(this), recipient, outputToken, outputAmtReceived);
} else {
/// @dev output token is already with user, no need to transfer
}
// slippage check
// Balance delta (not arithmetic) to support deflationary tokens; if a fee payout address is also
// `recipient`, that fee is counted into this number - never use feeReceiver/partner.recipient as one.
outputAmtReceived = outputToken.balanceOf(recipient) - initialUserOutputTokenBalance;
if (outputAmtReceived < request.minOutputAmount) revert MinReturnNotReached();
emit OrderRecord(
orderId, request.inputToken, outputToken, msg.sender, totalInputTokenAmount, outputAmtReceived, recipient
);
}
/// @notice Verify the authorization of a signed swap on the pull-based entrypoints
/// (`swapExactIn`, `swapExactInWithRefundTo`, `swapExactInWithSource`).
/// @dev Expects `routes.length == routesAmount.length + 1`, checked by the caller. paramsHash
/// covers everything that decides what the swap does and who gets the output:
/// keccak256(abi.encode(false, orderId, request, routesAmount, routeHashes, feeConfig, recipient))
/// The leading `false` marks the pull-based mode; see `_verifyPrefundedSwapAuth` for `true`.
/// Each route's amount is signed, not just their sum, so the submitter cannot shift input
/// from one route onto another, e.g. onto an auth-required adapter.
/// `refundTo` is deliberately not signed: `swapExactIn` resolves it to msg.sender, which the
/// backend cannot know for contract integrators, and it only receives the submitter's own
/// unspent intermediate tokens.
function _verifyPullSwapAuth(
uint256 orderId,
BaseExactInRequest memory request,
uint256[] memory routesAmount,
RouterPath[][] calldata routes,
uint256 feeConfig,
address recipient
) internal {
// Checked on the raw value: address(0) would resolve to msg.sender, letting anyone who
// copies the calldata redirect the output to themselves.
if (recipient == address(0)) revert InvalidSwapAuth();
uint256 n = routesAmount.length;
_consumeSwapAuth(
keccak256(abi.encode(false, orderId, request, routesAmount, _routeHashes(routes, n), feeConfig, recipient)),
routes[n]
);
}
/// @notice Verify the authorization of a signed swap on the pre-funded entrypoints
/// (`swapExactInPrefunded`, `swapExactInPrefundedWithSource`).
/// @dev Expects `routes.length == routesWeight.length + 1`, checked by the caller, and must run
/// before `request` and `feeConfig` are scaled: the backend signs the quote it issued, for
/// `expectedInputAmount`. paramsHash:
/// keccak256(abi.encode(true, orderId, request, routesWeight, expectedInputAmount,
/// routeHashes, feeConfig, recipient))
/// The route amounts are computed on-chain from what arrived, so the weights are signed in
/// their place, and `expectedInputAmount` caps the input (the excess is refunded). It must
/// be non-zero here: 0 means "swap whatever arrived", which would leave a signed swap
/// without any bound on its input.
/// The leading `true` keeps a pull-based authorization from verifying here and vice versa,
/// so a front-runner cannot burn the nonce of one by submitting it as the other.
function _verifyPrefundedSwapAuth(
uint256 orderId,
BaseExactInRequest memory request,
uint256[] calldata routesWeight,
RouterPath[][] calldata routes,
uint256 feeConfig,
address recipient,
uint256 expectedInputAmount
) internal {
// Raw recipient, as in `_verifyPullSwapAuth`.
if (recipient == address(0) || expectedInputAmount == 0) revert InvalidSwapAuth();
uint256 n = routesWeight.length;
_consumeSwapAuth(
keccak256(
abi.encode(
true,
orderId,
request,
routesWeight,
expectedInputAmount,
_routeHashes(routes, n),
feeConfig,
recipient
)
),
routes[n]
);
}
/// @notice Hash each of the first `n` (executable) routes on its own.
/// @dev `routeHashes[i] = keccak256(abi.encode(routes[i]))`. Per route because `abi.encode` of a
/// calldata slice of a nested dynamic struct array is not reliably supported; re-encoding
/// the decoded values (rather than hashing raw calldata) also keeps non-canonical ABI
/// encodings from passing a signature made over different decoded values.
function _routeHashes(RouterPath[][] calldata routes, uint256 n) internal pure returns (bytes32[] memory hashes) {
hashes = new bytes32[](n);
for (uint256 i = 0; i < n; ++i) {
hashes[i] = keccak256(abi.encode(routes[i]));
}
}
/// @notice Check the signature in a signed swap's trailing auth route against `paramsHash`,
/// and consume its nonce. Reverts on any failure; returns only if the swap is authorized.
/// @dev `authRoute` must be exactly one hop whose `extraData` holds exactly one entry,
/// `abi.encode(uint256 nonce, bytes signature)`; every other field of that hop is ignored
/// and is not part of the signed data. The signature is EIP-712 over
/// `SwapAuth(bytes32 paramsHash,uint256 nonce)` in the `DOMAIN_SEPARATOR()` domain.
function _consumeSwapAuth(bytes32 paramsHash, RouterPath[] calldata authRoute) internal {
if (authRoute.length != 1 || authRoute[0].extraData.length != 1) revert InvalidSwapAuth();
(uint256 nonce, bytes memory signature) = abi.decode(authRoute[0].extraData[0], (uint256, bytes));
bytes32 digest = MessageHashUtils.toTypedDataHash(
DOMAIN_SEPARATOR(), keccak256(abi.encode(SWAP_AUTH_TYPEHASH, paramsHash, nonce))
);
// tryRecover rejects malformed lengths and high-s (malleable) signatures with a non-zero error
(address signer, ECDSA.RecoverError err,) = ECDSA.tryRecover(digest, signature);
SwapAuthStorage storage $ = _getSwapAuthStorage();
if (err != ECDSA.RecoverError.NoError || !$.isSwapAuthSigner[signer]) revert InvalidSwapAuthSignature();
// Consume the nonce last, once the signature is known to be valid.
uint256 bit = 1 << (nonce & 0xff);
uint256 wordPos = nonce >> 8;
uint256 bitmap = $.nonceBitmap[wordPos];
if (bitmap & bit != 0) revert SwapAuthNonceUsed();
$.nonceBitmap[wordPos] = bitmap | bit;
}
/// @notice The swap behind `swapExactInPrefunded` and `swapExactInPrefundedWithSource`, which
/// differ only in the source signature the latter checks first.
/// @dev Sizes the input, settles it against `expectedInputAmount` and turns the weights into
/// amounts, so `_swapExactIn` only ever sees absolute values; the one thing it still has to
/// be told is that the input is already in this contract.
///
/// The input is read once, before any route runs: every route amount is derived from this
/// snapshot, so a route's own transfers cannot shift another route's share. msg.value
/// rather than the ETH balance for a native input, which leaves stray ETH alone.
///
/// `request.minOutputAmount` and the quotedAmount in `feeConfig` were quoted for
/// `expectedInputAmount`, so that is also the most this swaps:
/// - More arrived: the excess goes to `refundTo` and the swap runs exactly as quoted. The
/// floor is never raised, so tokens someone else sent here cannot push it out of reach;
/// they end up with `refundTo` instead.
/// - Less arrived: both are scaled down by `total / expectedInputAmount`, minOutputAmount
/// rounded up and quotedAmount rounded down.
/// The excess is refunded before the swap, not after: the wrap / unwrap sweeps at the end
/// of `_swapExactIn` take this contract's whole ETH / WETH balance and would otherwise
/// count the excess as output.
/// @param expectedInputAmount The input amount the quote was based on; 0 swaps whatever arrived
/// against the floor and quote as given (not allowed for a signed swap)
function _swapExactInPrefunded(
uint256 orderId,
BaseExactInRequest memory request,
uint256[] calldata routesWeight,
RouterPath[][] calldata routes,
uint256 feeConfig,
address recipient,
address refundTo,
uint256 expectedInputAmount
) internal returns (uint256) {
address inputToken = request.inputToken;
uint256 total = inputToken.isETH() ? msg.value : inputToken.balanceOf(address(this));
if (total == 0) revert ZeroAmount();
// Signed swap: verified here, before the refund and the scaling below touch anything, see
// `_verifyPrefundedSwapAuth`. `_swapExactIn` relies on this and skips its own check.
if (routesWeight.length != 0 && routes.length == routesWeight.length + 1) {
// The authorization is not tied to the caller, and a shortfall only scales the
// slippage floor down, so without a lower bound any non-zero input would satisfy it.
// Requiring at least half of the quoted input keeps a near-empty pre-fund from
// executing the authorization and using up its nonce, while leaving ample room for
// the deviation a bridge or a transfer fee produces. Checked before the signature so
// that such a call never reaches the nonce.
if (total < expectedInputAmount / 2) revert PrefundedInputTooLow();
_verifyPrefundedSwapAuth(orderId, request, routesWeight, routes, feeConfig, recipient, expectedInputAmount);
}
if (refundTo == address(0)) refundTo = msg.sender;
if (expectedInputAmount != 0) {
if (total > expectedInputAmount) {
_transferInternal(address(this), refundTo, inputToken, total - expectedInputAmount);
total = expectedInputAmount;
} else if (total < expectedInputAmount) {
request.minOutputAmount = FullMath.mulDivRoundingUp(request.minOutputAmount, total, expectedInputAmount);
feeConfig = feeConfig.scaleQuotedAmount(total, expectedInputAmount);
}
}
return _swapExactIn(
orderId, request, _splitByWeight(total, routesWeight), routes, feeConfig, recipient, refundTo, true
);
}
/// @notice Split the input of a pre-funded swap across its routes by weight.
/// @dev Every route but the last gets `total * weight / 10000` rounded down; the last takes the
/// remainder, so the amounts always sum to `total` and no dust is left unrouted — the same
/// rule `_execExactInHop` applies to the forks of a hop. The running sum is checked inside
/// the loop as well as at the end: that bounds every non-final amount by `total`, so an
/// oversized weight surfaces as PathWeightInvalid rather than as an arithmetic panic on the
/// remainder. An empty array fails the final check.
///
/// A route that ends up with nothing to trade, because its weight is 0 or the input is too
/// small for its weight, reverts with ZeroAmount here rather than later with whatever
/// error its pool has for an empty swap.
/// @param total The input to split
/// @param weights The bps weight of each route; must sum to exactly 10000
/// @return amounts The input amount of each route, positionally matched to `weights`
function _splitByWeight(uint256 total, uint256[] calldata weights)
internal
pure
returns (uint256[] memory amounts)
{
uint256 length = weights.length;
amounts = new uint256[](length);
uint256 totalWeight;
uint256 allocated;
for (uint256 i = 0; i < length; ++i) {
uint256 weight = weights[i];
totalWeight += weight;
if (totalWeight > 10_000) revert PathWeightInvalid();
uint256 routeAmount;
if (i == length - 1) {
routeAmount = total - allocated;
} else {
routeAmount = (total * weight) / 10_000;
allocated += routeAmount;
}
if (routeAmount == 0) revert ZeroAmount();
amounts[i] = routeAmount;
}
if (totalWeight != 10_000) revert PathWeightInvalid();
}
/// @notice This function manages a single swap route that might involve multiple hops through different liquidity pools or swapping protocols.
/// @dev It iterates through the provided `hops`, executing each segment of the route in sequence.
/// @param payer The address who will pay the input token for current hop, this will be updated after each hop
/// @param recipient The address who will receive the output token of the last hop in the route
/// @param refundTo The address who will receive the unspent input token when a hop is only partially filled
/// @param curInputAmount The amount of input token to be used in the current route, this will be updated after each hop
/// @param hops The detailed swap information for all hops in the route
/// @param authorized Whether this swap carried a valid swap authorization, i.e. whether adapters
/// flagged in `isAdapterAuthRequired` may run. Passed down as a parameter rather than kept
/// in transient storage so it can never leak into a later swap in the same transaction.
function _execExactInRoute(
address payer,
address recipient,
address refundTo,
uint256 curInputAmount,
RouterPath[] calldata hops,
bool authorized
) internal {
address fromToken;
bool tokenAlreadySentToNextHop;
// by default we need to transfer the output token to the next hop as input
// unless the current pool has already done that
bool requireTransfer = true;
uint256 ethBalanceBeforeHop;
uint256 wethBalanceBeforeHop;
uint256 hopLength = hops.length;
for (uint256 i = 0; i < hopLength; ++i) {
if (i > 0) {
fromToken = hops[i].fromToken;
// start from the second hop, we need to check if we need to wrap/unwrap the token
// since the output token of the previous hop can contain both ETH and WETH
// imagine we have forks in previous hop i.e. [30% usdc->weth, 70% usdc->eth]
if (fromToken.isETH()) {
uint256 wethBalanceAfterHop = WETH9.balanceOf(address(this));
// if previous hop output: WETH and current hop input: ETH, convert WETH from previous hop output to ETH
if (wethBalanceAfterHop > wethBalanceBeforeHop) {
_unwrap(wethBalanceAfterHop - wethBalanceBeforeHop);
}
uint256 ethBalanceAfterHop = address(this).balance;
curInputAmount = ethBalanceAfterHop - ethBalanceBeforeHop;
} else if (fromToken == address(WETH9)) {
uint256 ethBalanceAfterHop = address(this).balance;
// if previous hop output: ETH and current hop input: WETH, convert ETH from previous hop output to WETH
if (ethBalanceAfterHop > ethBalanceBeforeHop) _wrap(ethBalanceAfterHop - ethBalanceBeforeHop);
uint256 wethBalanceAfterHop = WETH9.balanceOf(address(this));
curInputAmount = wethBalanceAfterHop - wethBalanceBeforeHop;
} else {
// previous hop output is not ETH/WETH. In pull mode the input token for other routes is
// not in this contract yet; in prefunded mode it is, so a hop whose fromToken is the
// swap's inputToken (a cyclic route) would consume it. See IAggregator.swapExactInPrefunded.
curInputAmount = fromToken.balanceOf(address(this));
}
payer = address(this);
}
address to = address(this);
if (i == hopLength - 1) {
to = recipient;
} else if (
i < hopLength - 1 && hops[i + 1].assetTo.length == 1
&& !(hops[i + 1].mixAdapters[0].shouldInputWrapped()
|| hops[i + 1].mixAdapters[0].shouldInputUnwrapped())
) {
// if next hop has only one fork and wrap/unwrap is not needed, send output to next hop directly to save one transfer
to = hops[i + 1].assetTo[0];
tokenAlreadySentToNextHop = true;
} else {
// if we have multiple forks in the next hop, we need to mannually split the output token
// so we need to send the output token back to this contract first
// address to = address(this);
tokenAlreadySentToNextHop = false;
}
// if not the last hop, and next hop fromToken is ETH/WETH, record the current balance of ETH/WETH before next hop
if (i < hopLength - 1 && (hops[i + 1].fromToken.isETH() || hops[i + 1].fromToken == address(WETH9))) {
bool willTransferFromThisContract = payer == address(this) && requireTransfer;
/// @dev in case input token is also output token here, we need to deduct the input token amount
ethBalanceBeforeHop = address(this).balance
- (hops[i].fromToken.isETH() && willTransferFromThisContract ? curInputAmount : 0);
wethBalanceBeforeHop = WETH9.balanceOf(address(this))
- (hops[i].fromToken == address(WETH9) && willTransferFromThisContract ? curInputAmount : 0);
}
// execute forks
_execExactInHop(payer, to, refundTo, curInputAmount, hops[i], requireTransfer, authorized);
requireTransfer = !tokenAlreadySentToNextHop;
}
}
/// @notice Executes single hop in a route, however, input token could be further split into multiple forks.
/// It iterates through the provided `forks`, each fork represents a different liquidity pool or swapping protocol.
/// For example, a hop with 3 forks could be [30% fork1(UNIV2), 30% fork2(PCSV3), 40% fork3(PCSINFINITY)]
/// @param payer The address who will pay the input token for current hop
/// @param receiver The address who will receive the output token for current hop
/// @param refundTo The address who will receive the unspent input token when a fork is only partially filled
/// @param curInputAmount The amount of input token to be used in the current hop
/// @param path The detailed swap information for all forks in the hop
/// @param requireTransfer A boolean indicating whether the output token should be transferred to the address specified in the `assetTo` field
/// @param authorized Whether this swap carried a valid swap authorization, see `_execExactInRoute`
function _execExactInHop(
address payer,
address receiver,
address refundTo,
uint256 curInputAmount,
RouterPath calldata path,
bool requireTransfer,
bool authorized
) internal {
address fromToken = path.fromToken;
uint256 totalWeight;
// execute multiple Adapters for a transaction pair
uint256 pathLength = path.mixAdapters.length;
uint256 alreadyUsedAmt = 0;
for (uint256 i = 0; i < pathLength; ++i) {
uint256 adapter = path.mixAdapters[i];
(address poolAddress, uint256 weight, bool reverse) = path.rawData[i].decodePathRawData();
totalWeight += weight;
if (i == pathLength - 1) {
if (totalWeight != 10_000) revert PathWeightInvalid();
}
/// @dev wrap/unwrap input token if necessary
// This wrap/unwrap part is designed based on the consideration of those 4 cases:
// 1. fromToken = eth, pool = weth -> X : wrap, transfer
// 2. fromToken = weth, pool = eth -> X : transfer if first hop, wrap, transfer
// 3. (no wrap/unwrap) fromToken = weth, pool = weth -> X : transfer only
// 4. (no wrap/unwrap) fromToken = eth, pool = eth -> X : transfer only
uint256 _fromTokenAmount;
if (i == pathLength - 1) {
// fix the accumulated rounding error
// Example scenario:
// curInputAmount = 100
// weights: [3333, 3333, 3334] (should total 10000)
// First fork: (100 * 3333) / 10000 = 33.33 -> 33
// Second fork: (100 * 3333) / 10000 = 33.33 -> 33
// Third fork: (100 * 3334) / 10000 = 33.34 -> 33
// this is to make sure that no token is left due to precision loss
_fromTokenAmount = curInputAmount - alreadyUsedAmt;
} else {
_fromTokenAmount = weight == 10_000 ? curInputAmount : (curInputAmount * weight) / 10_000;
alreadyUsedAmt += _fromTokenAmount;
}
if (adapter.shouldInputWrapped()) {
// case 1
_wrap(_fromTokenAmount);
fromToken = address(WETH9);
payer = address(this);
} else if (adapter.shouldInputUnwrapped()) {
// case 2
if (payer != address(this)) {
// first hop of a route, weth from external payer
_transferInternal(payer, address(this), fromToken, _fromTokenAmount);
}
_unwrap(_fromTokenAmount);
fromToken = CommonUtils.ETH;
payer = address(this);
}
/// @dev these protocols used to be inlined; they now live in the SwapExecutor and are
/// reached via delegatecall so they still run in this contract's context (payer
/// approvals, ETH balance and swap callbacks all behave as before)
if (adapter.isUniV2Adapter() || adapter.isPcsV2Adapter()) {
if (requireTransfer) {
_transferInternal(payer, path.assetTo[i], fromToken, _fromTokenAmount);
}
// for uni/pcs v2, the executor applies a different fee ratio
_delegateToExecutor(
abi.encodeCall(ISwapExecutor.uniV2Swap, (receiver, poolAddress, reverse, adapter.isPcsV2Adapter()))
);
} else if (adapter.isUniV3StyledAdapter()) {
/// @dev path.extraData[i] equal to abi.encode(uint160 sqrtX96PriceLimit, address fromToken, address toToken, uint24 fee)
_delegateToExecutor(
abi.encodeCall(
ISwapExecutor.uniV3Swap,
(_fromTokenAmount, payer, receiver, refundTo, poolAddress, path.extraData[i])
)
);
} else if (adapter.isInfinitySwapAdapter()) {
_delegateToExecutor(
abi.encodeCall(
ISwapExecutor.infinitySwap,
(_fromTokenAmount, payer, receiver, refundTo, poolAddress, path.extraData[i])
)
);
} else if (adapter.isUniV4StyledAdapter()) {
_delegateToExecutor(
abi.encodeCall(
ISwapExecutor.uniV4Swap, (_fromTokenAmount, payer, receiver, refundTo, path.extraData[i])
)
);
} else {
address adapterAddress = adapter.bytes32ToAddress();
if (!isAdapterWhitelisted[adapterAddress]) revert AdapterNotWhitelisted();
// Signed swaps skip the lookup: any whitelisted adapter may run inside one.
if (!authorized && _getSwapAuthStorage().isAdapterAuthRequired[adapterAddress]) {
revert AdapterRequiresSwapAuth();
}
// execute the swap through the external adapter
if (requireTransfer) {
_transferInternal(payer, path.assetTo[i], fromToken, _fromTokenAmount);
}
/// @dev We keep the `reverse`-based selector split for adapter compatibility.
/// Some adapters (e.g. Balancer) encode tokenIn/tokenOut in `path.extraData[i]`, so both selectors
/// end up calling the same swap with the same params; others (e.g. Fluid-style) may use the selector
/// itself to indicate swap direction.
if (reverse) {
IAdapter(adapterAddress).swapExactOneForZero(receiver, poolAddress, path.extraData[i]);
} else {
IAdapter(adapterAddress).swapExactZeroForOne(receiver, poolAddress, path.extraData[i]);
}
}
}
}
/// @dev Delegatecalls the SwapExecutor and bubbles up any revert unchanged, so errors from the
/// pools/adapters surface exactly as they did when the code was inlined.
function _delegateToExecutor(bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = SWAP_EXECUTOR.delegatecall(data);
if (!success) {
assembly ("memory-safe") {
revert(add(returnData, 32), mload(returnData))
}
}
return returnData;
}
/// @notice Split the fee charged by a swap between a referral partner and the protocol, and pay
/// both out.
/// @dev The two fee types are scaled by independent rates, so they are passed separately even
/// though the partner is paid in a single transfer. The protocol leg is computed as the
/// remainder rather than a second multiplication, so rounding dust always accrues to the
/// protocol and the two payouts sum to `percentageFee + surplus` exactly.
///
/// An unregistered or removed partnerId is deliberately not an error: the whole fee falls
/// through to feeReceiver. Reverting would brick in-flight swaps whenever a partner is
/// offboarded.
/// @param token The token the fee is denominated in, i.e. the swap's output token
/// @param percentageFee The percentage-based fee taken from the output amount
/// @param surplus The captured positive price-impact surplus; 0 when there is none
/// @param partnerId The referral partner from feeConfig; 0 means no partner
function _settleFee(address token, uint256 percentageFee, uint256 surplus, uint16 partnerId) internal {
uint256 totalFee = percentageFee + surplus;
if (totalFee == 0) return;
uint256 partnerFee;
if (partnerId != 0) {
Partner storage partner = partners[partnerId];
if (partner.recipient != address(0)) {
// Each leg rounds down independently, in the protocol's favour. Plain checked
// arithmetic rather than FullMath: both shares are validated to be <= MAX_FEE on
// write, so an intermediate overflow would need an amount above ~1.1e73, and it
// would revert rather than wrap.
uint256 partnerPercentageFee = (percentageFee * partner.feeShareBps) / FeeHelper.MAX_FEE;
uint256 partnerSurplus = (surplus * partner.surplusBps) / FeeHelper.MAX_FEE;
partnerFee = partnerPercentageFee + partnerSurplus;
if (partnerFee > 0) {
// WARNING: if token is native ETH and recipient can't receive it, this reverts every such swap.
_transferInternal(address(this), partner.recipient, token, partnerFee);
emit PartnerFeeRecord(partnerId, partner.recipient, token, partnerPercentageFee, partnerSurplus);
}
}
}
uint256 protocolFee = totalFee - partnerFee;
if (protocolFee > 0) {
_transferInternal(address(this), feeReceiver, token, protocolFee);
emit FeeRecord(token, protocolFee, feeReceiver);
}
}
/// @inheritdoc IAggregator
function batchSetPartners(uint16[] calldata partnerIds, Partner[] calldata infos) external onlyOwner {
if (partnerIds.length != infos.length) revert BadParams();
for (uint256 i = 0; i < partnerIds.length;) {
_setPartner(partnerIds[i], infos[i].recipient, infos[i].feeShareBps, infos[i].surplusBps);
unchecked {
++i;
}
}
}
/// @notice Validation and write behind `batchSetPartners`.
/// @dev A zero `recipient` is the removal encoding: the slot is cleared, the id then reads as
/// unregistered, and swaps still naming it fall through to a 100% protocol fee. Removal is
/// idempotent — clearing an id that was never registered is a no-op.
function _setPartner(uint16 partnerId, address recipient, uint16 feeShareBps, uint16 surplusBps) internal {
// partnerId 0 is the "no partner" sentinel and must never resolve to a payout address.
if (partnerId == 0) revert BadParams();
if (recipient == address(0)) {
delete partners[partnerId];
// keep the log consistent with the cleared slot rather than echoing ignored bps
feeShareBps = 0;
surplusBps = 0;
} else {
// recipient == address(this) would make _transferInternal short-circuit on payer == to,
// silently stranding the fee in this contract until it is swept.
// ETH-receivability is not checkable here; see the warning in _settleFee.
if (recipient == address(this) || feeShareBps > FeeHelper.MAX_FEE || surplusBps > FeeHelper.MAX_FEE) {
revert BadParams();
}
partners[partnerId] = Partner(recipient, feeShareBps, surplusBps);
}
emit PartnerSet(partnerId, recipient, feeShareBps, surplusBps);
}
/// @inheritdoc IAggregator
function whitelistAdapter(address adapter, bool whitelisted) external onlyOwner {
isAdapterWhitelisted[adapter] = whitelisted;
emit AdapterWhitelisted(adapter, whitelisted);
}
/// @inheritdoc IAggregator
function batchSetSourceSigners(address[] calldata signers, bool[] calldata enabled) external onlyOwner {
if (signers.length != enabled.length) revert BadParams();
for (uint256 i = 0; i < signers.length;) {
// Invariant: address(0) must never be an enabled signer. ECDSA.tryRecover happens to reject
// a zero recovery today, but this check is what enforces the invariant here; do not remove it
// or swap tryRecover for raw ecrecover without keeping it. Disabling address(0) stays allowed.
if (enabled[i] && signers[i] == address(0)) revert ZeroAddress();
isSourceSigner[signers[i]] = enabled[i];
emit SourceSignerSet(signers[i], enabled[i]);
unchecked {
++i;
}
}
}
/// @notice Whether `adapter` may only run inside a signed swap.
/// @dev Explicit getters for the ERC-7201 struct members, which get no auto-generated getter;
/// names and signatures match the public mappings they replace.
function isAdapterAuthRequired(address adapter) external view returns (bool) {
return _getSwapAuthStorage().isAdapterAuthRequired[adapter];
}
/// @notice Whether `signer` is an enabled swap-auth signer.
function isSwapAuthSigner(address signer) external view returns (bool) {
return _getSwapAuthStorage().isSwapAuthSigner[signer];
}
/// @notice Word `wordPos` of the used swap-auth nonce bitmap; nonce `n` is bit `n & 0xff` of word `n >> 8`.
function swapAuthNonceBitmap(uint256 wordPos) external view returns (uint256) {
return _getSwapAuthStorage().nonceBitmap[wordPos];
}
/// @dev The assembly only assigns a storage pointer, so it is memory-safe; marking it keeps the
/// via-IR optimizer free to move stack variables to memory elsewhere in this contract.
function _getSwapAuthStorage() private pure returns (SwapAuthStorage storage $) {
assembly ("memory-safe") {
$.slot := SWAP_AUTH_STORAGE_LOCATION
}
}
/// @inheritdoc IAggregator
function setAdapterAuthRequired(address adapter, bool required) external onlyOwner {
_getSwapAuthStorage().isAdapterAuthRequired[adapter] = required;
emit AdapterAuthRequiredSet(adapter, required);
}
/// @inheritdoc IAggregator
function batchSetSwapAuthSigners(address[] calldata signers, bool[] calldata enabled) external onlyOwner {
if (signers.length != enabled.length) revert BadParams();
SwapAuthStorage storage $ = _getSwapAuthStorage();
for (uint256 i = 0; i < signers.length;) {
// Same invariant as batchSetSourceSigners: address(0) must never be an enabled signer.
if (enabled[i] && signers[i] == address(0)) revert ZeroAddress();
$.isSwapAuthSigner[signers[i]] = enabled[i];
emit SwapAuthSignerSet(signers[i], enabled[i]);
unchecked {
++i;
}
}
}
/// @inheritdoc IAggregator
function setFeeReceiver(address _feeReceiver) external onlyOwner {
if (_feeReceiver == address(0)) revert InvalidFeeReceiver();
feeReceiver = _feeReceiver;
emit FeeReceiverUpdated(_feeReceiver);
}
/// @notice the aggregation contract is not expected to hold tokens
/// this function helps to rescue tokens left in the contract for any reasons
function sweep(address token, address recipient, uint256 amountMinimum) external isNotLocked onlyOwner {
uint256 balance = token.balanceOf(address(this));
if (balance < amountMinimum) revert InsufficientToken();
if (balance > 0) _transferInternal(address(this), recipient, token, balance);
}
}
Настройки компилятораПоказать
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 2000,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"infinity-core/=lib/infinity-periphery/lib/infinity-core/",
"uniswap-v4-core/=lib/v4-core/",
"ds-test/=lib/infinity-periphery/lib/infinity-core/lib/forge-std/lib/ds-test/src/",
"openzeppelin-contracts/=lib/infinity-periphery/lib/infinity-core/lib/openzeppelin-contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"solmate/=lib/infinity-periphery/lib/infinity-core/lib/solmate/",
"lib/infinity-periphery/lib/infinity-core:forge-std/=lib/forge-std/src/",
"lib/v4-core/:forge-std/=lib/forge-std/src/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/infinity-periphery/lib/infinity-core/lib/forge-gas-snapshot/src/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/infinity-periphery/lib/infinity-core/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"infinity-periphery/=lib/infinity-periphery/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"pancake-create3-factory/=lib/infinity-periphery/lib/pancake-create3-factory/",
"permit2/=lib/infinity-periphery/lib/permit2/",
"v4-core/=lib/v4-core/src/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.