Verified contractExactGPL-3.0-or-later
PendleSwap
Address0xd4e9b0d466789d7f6201442eeccba6a75a552db0
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 1,000,000 runs
- EVM version
- shanghai
- Via IR
- yes
- License
- GPL-3.0-or-later
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 22,337,359
- Creation transaction
- 0xee0b57ed30…07e14f850c
11 files
- contracts/pendle/contracts/router/swap-aggregator/PendleSwap.solmain4.03 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.74 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol2.26 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol6.94 KB
- @openzeppelin/contracts/utils/Address.sol9.36 KB
- contracts/pendle/contracts/core/libraries/TokenHelper.sol2.96 KB
- contracts/pendle/contracts/interfaces/IWETH.sol1.45 KB
- contracts/pendle/contracts/router/swap-aggregator/IPSwapAggregator.sol718 B
- contracts/pendle/contracts/router/swap-aggregator/OKXScaleHelper.sol7.78 KB
- contracts/pendle/contracts/router/swap-aggregator/ParaswapScaleHelper.sol9.39 KB
contracts/pendle/contracts/router/swap-aggregator/PendleSwap.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;
import "../../core/libraries/TokenHelper.sol";
import "./IPSwapAggregator.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./OKXScaleHelper.sol";
import "./ParaswapScaleHelper.sol";
contract PendleSwap is IPSwapAggregator, TokenHelper, OKXScaleHelper, ParaswapScaleHelper {
using Address for address;
using SafeERC20 for IERC20;
address private constant KYBER_SCALING_HELPER = 0x2f577A41BeC1BE1152AeEA12e73b7391d15f655D;
function swap(address tokenIn, uint256 amountIn, SwapData calldata data) external payable {
_approveForExtRouter(tokenIn, data);
data.extRouter.functionCallWithValue(
data.needScale ? _getScaledInputData(data.swapType, data.extCalldata, amountIn) : data.extCalldata,
tokenIn == NATIVE ? amountIn : 0
);
emit SwapSingle(data.swapType, tokenIn, amountIn);
}
function _approveForExtRouter(address token, SwapData calldata data) internal {
if (token == NATIVE) return;
if (data.swapType == SwapType.OKX) {
_safeApproveInfV2(IERC20(token), _okx_getTokenApprove());
} else {
_safeApproveInfV2(IERC20(token), data.extRouter);
}
}
function _safeApproveInfV2(IERC20 token, address spender) internal {
if (token.allowance(address(this), spender) < type(uint256).max) {
token.forceApprove(spender, type(uint256).max);
}
}
function _getScaledInputData(
SwapType swapType,
bytes calldata rawCallData,
uint256 amountIn
) internal view returns (bytes memory scaledCallData) {
if (swapType == SwapType.KYBERSWAP) {
bool isSuccess;
(isSuccess, scaledCallData) = IKyberScalingHelper(KYBER_SCALING_HELPER).getScaledInputData(
rawCallData,
amountIn
);
require(isSuccess, "PendleSwap: Kyber scaling failed");
} else if (swapType == SwapType.ODOS) {
scaledCallData = _odosScaling(rawCallData, amountIn);
} else if (swapType == SwapType.PARASWAP) {
scaledCallData = _paraswapScaling(rawCallData, amountIn);
} else if (swapType == SwapType.OKX) {
scaledCallData = _okxScaling(rawCallData, amountIn);
} else {
assert(false);
}
}
function _odosScaling(
bytes calldata rawCallData,
uint256 amountIn
) internal pure returns (bytes memory scaledCallData) {
bytes4 selector = bytes4(rawCallData[:4]);
bytes calldata dataToDecode = rawCallData[4:];
assert(selector == IOdosRouterV2.swap.selector);
(
IOdosRouterV2.swapTokenInfo memory tokenInfo,
bytes memory pathDefinition,
address executor,
uint32 referralCode
) = abi.decode(dataToDecode, (IOdosRouterV2.swapTokenInfo, bytes, address, uint32));
tokenInfo.outputQuote = (tokenInfo.outputQuote * amountIn) / tokenInfo.inputAmount;
tokenInfo.outputMin = (tokenInfo.outputMin * amountIn) / tokenInfo.inputAmount;
tokenInfo.inputAmount = amountIn;
return abi.encodeWithSelector(selector, tokenInfo, pathDefinition, executor, referralCode);
}
receive() external payable {}
}
interface IKyberScalingHelper {
function getScaledInputData(
bytes calldata inputData,
uint256 newAmount
) external view returns (bool isSuccess, bytes memory data);
}
interface IOdosRouterV2 {
struct swapTokenInfo {
address inputToken;
uint256 inputAmount;
address inputReceiver;
address outputToken;
uint256 outputQuote;
uint256 outputMin;
address outputReceiver;
}
function swap(
swapTokenInfo memory tokenInfo,
bytes calldata pathDefinition,
address executor,
uint32 referralCode
) external payable returns (uint256 amountOut);
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
contracts/pendle/contracts/core/libraries/TokenHelper.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../../interfaces/IWETH.sol";
abstract contract TokenHelper {
using SafeERC20 for IERC20;
address internal constant NATIVE = address(0);
uint256 internal constant LOWER_BOUND_APPROVAL = type(uint96).max / 2; // some tokens use 96 bits for approval
function _transferIn(address token, address from, uint256 amount) internal {
if (token == NATIVE) require(msg.value == amount, "eth mismatch");
else if (amount != 0) IERC20(token).safeTransferFrom(from, address(this), amount);
}
function _transferFrom(IERC20 token, address from, address to, uint256 amount) internal {
if (amount != 0) token.safeTransferFrom(from, to, amount);
}
function _transferOut(address token, address to, uint256 amount) internal {
if (amount == 0) return;
if (token == NATIVE) {
(bool success, ) = to.call{value: amount}("");
require(success, "eth send failed");
} else {
IERC20(token).safeTransfer(to, amount);
}
}
function _transferOut(address[] memory tokens, address to, uint256[] memory amounts) internal {
uint256 numTokens = tokens.length;
require(numTokens == amounts.length, "length mismatch");
for (uint256 i = 0; i < numTokens; ) {
_transferOut(tokens[i], to, amounts[i]);
unchecked {
i++;
}
}
}
function _selfBalance(address token) internal view returns (uint256) {
return (token == NATIVE) ? address(this).balance : IERC20(token).balanceOf(address(this));
}
function _selfBalance(IERC20 token) internal view returns (uint256) {
return token.balanceOf(address(this));
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token
/// @dev PLS PAY ATTENTION to tokens that requires the approval to be set to 0 before changing it
function _safeApprove(address token, address to, uint256 value) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "Safe Approve");
}
function _safeApproveInf(address token, address to) internal {
if (token == NATIVE) return;
if (IERC20(token).allowance(address(this), to) < LOWER_BOUND_APPROVAL) {
_safeApprove(token, to, 0);
_safeApprove(token, to, type(uint256).max);
}
}
function _wrap_unwrap_ETH(address tokenIn, address tokenOut, uint256 netTokenIn) internal {
if (tokenIn == NATIVE) IWETH(tokenOut).deposit{value: netTokenIn}();
else IWETH(tokenIn).withdraw(netTokenIn);
}
}
contracts/pendle/contracts/interfaces/IWETH.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWETH is IERC20 {
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
function deposit() external payable;
function withdraw(uint256 wad) external;
}
contracts/pendle/contracts/router/swap-aggregator/IPSwapAggregator.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
struct SwapData {
SwapType swapType;
address extRouter;
bytes extCalldata;
bool needScale;
}
struct SwapDataExtra {
address tokenIn;
address tokenOut;
uint256 minOut;
SwapData swapData;
}
enum SwapType {
NONE,
KYBERSWAP,
ODOS,
// ETH_WETH not used in Aggregator
ETH_WETH,
OKX,
ONE_INCH,
PARASWAP,
RESERVE_2,
RESERVE_3,
RESERVE_4,
RESERVE_5
}
interface IPSwapAggregator {
event SwapSingle(SwapType indexed swapType, address indexed tokenIn, uint256 amountIn);
function swap(address tokenIn, uint256 amountIn, SwapData calldata swapData) external payable;
}
contracts/pendle/contracts/router/swap-aggregator/OKXScaleHelper.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;
import "../../core/libraries/TokenHelper.sol";
import "./IPSwapAggregator.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
abstract contract OKXScaleHelper {
function _okx_getTokenApprove() internal view returns (address) {
if (block.chainid == 1) {
return 0x40aA958dd87FC8305b97f2BA922CDdCa374bcD7f;
}
if (block.chainid == 10) {
return 0x68D6B739D2020067D1e2F713b999dA97E4d54812;
}
if (block.chainid == 56) {
return 0x2c34A2Fb1d0b4f55de51E1d0bDEfaDDce6b7cDD6;
}
if (block.chainid == 42161) {
return 0x70cBb871E8f30Fc8Ce23609E9E0Ea87B6b222F58;
}
if (block.chainid == 8453) {
return 0x57df6092665eb6058DE53939612413ff4B09114E;
}
if (block.chainid == 5000) {
return 0x57df6092665eb6058DE53939612413ff4B09114E;
}
revert("PendleSwap: OKX Chain not supported");
}
function _okxScaling(
bytes calldata rawCallData,
uint256 actualAmount
) internal pure returns (bytes memory scaledCallData) {
bytes4 selector = bytes4(rawCallData[:4]);
bytes calldata dataToDecode = rawCallData[4:];
if (selector == IOKXDexRouter.uniswapV3SwapTo.selector) {
(uint256 receiver, uint256 amount, uint256 minReturn, uint256[] memory pools) = abi.decode(
dataToDecode,
(uint256, uint256, uint256, uint256[])
);
minReturn = (minReturn * actualAmount) / amount;
amount = actualAmount;
return abi.encodeWithSelector(selector, receiver, amount, minReturn, pools);
} else if (selector == IOKXDexRouter.smartSwapTo.selector) {
(
uint256 orderId,
address receiver,
IOKXDexRouter.BaseRequest memory baseRequest,
uint256[] memory batchesAmount,
IOKXDexRouter.RouterPath[][] memory batches,
IOKXDexRouter.PMMSwapRequest[] memory extraData
) = abi.decode(
dataToDecode,
(
uint256,
address,
IOKXDexRouter.BaseRequest,
uint256[],
IOKXDexRouter.RouterPath[][],
IOKXDexRouter.PMMSwapRequest[]
)
);
batchesAmount = _scaleArray(batchesAmount, actualAmount, baseRequest.fromTokenAmount);
baseRequest.minReturnAmount = (baseRequest.minReturnAmount * actualAmount) / baseRequest.fromTokenAmount;
baseRequest.fromTokenAmount = actualAmount;
return abi.encodeWithSelector(selector, orderId, receiver, baseRequest, batchesAmount, batches, extraData);
} else if (selector == IOKXDexRouter.unxswapTo.selector) {
(uint256 srcToken, uint256 amount, uint256 minReturn, address receiver, bytes32[] memory pools) = abi
.decode(dataToDecode, (uint256, uint256, uint256, address, bytes32[]));
minReturn = (minReturn * actualAmount) / amount;
amount = actualAmount;
return abi.encodeWithSelector(selector, srcToken, amount, minReturn, receiver, pools);
} else if (selector == IOKXDexRouter.unxswapByOrderId.selector) {
(uint256 srcToken, uint256 amount, uint256 minReturn, bytes32[] memory pools) = abi.decode(
dataToDecode,
(uint256, uint256, uint256, bytes32[])
);
minReturn = (minReturn * actualAmount) / amount;
amount = actualAmount;
return abi.encodeWithSelector(selector, srcToken, amount, minReturn, pools);
} else if (selector == IOKXDexRouter.smartSwapByOrderId.selector) {
(
uint256 orderId,
IOKXDexRouter.BaseRequest memory baseRequest,
uint256[] memory batchesAmount,
IOKXDexRouter.RouterPath[][] memory batches,
IOKXDexRouter.PMMSwapRequest[] memory extraData
) = abi.decode(
dataToDecode,
(
uint256,
IOKXDexRouter.BaseRequest,
uint256[],
IOKXDexRouter.RouterPath[][],
IOKXDexRouter.PMMSwapRequest[]
)
);
batchesAmount = _scaleArray(batchesAmount, actualAmount, baseRequest.fromTokenAmount);
baseRequest.minReturnAmount = (baseRequest.minReturnAmount * actualAmount) / baseRequest.fromTokenAmount;
baseRequest.fromTokenAmount = actualAmount;
return abi.encodeWithSelector(selector, orderId, baseRequest, batchesAmount, batches, extraData);
} else {
revert("PendleSwap: OKX selector not supported");
}
}
function _scaleArray(
uint256[] memory arr,
uint256 newAmount,
uint256 oldAmount
) internal pure returns (uint256[] memory scaledArr) {
scaledArr = new uint256[](arr.length);
for (uint256 i = 0; i < arr.length; i++) {
scaledArr[i] = (arr[i] * newAmount) / oldAmount;
}
}
}
interface IOKXDexRouter {
struct BaseRequest {
uint256 fromToken;
address toToken;
uint256 fromTokenAmount;
uint256 minReturnAmount;
uint256 deadLine;
}
struct RouterPath {
address[] mixAdapters;
address[] assetTo;
uint256[] rawData;
bytes[] extraData;
uint256 fromToken;
}
struct PMMSwapRequest {
uint256 pathIndex;
address payer;
address fromToken;
address toToken;
uint256 fromTokenAmountMax;
uint256 toTokenAmountMax;
uint256 salt;
uint256 deadLine;
bool isPushOrder;
bytes extension;
}
// // address marketMaker;
// // uint256 subIndex;
// // bytes signature;
// // uint256 source; 1byte type + 1byte bool(reverse) + 0...0 + 20 bytes address
// function smartSwapByInvest(
// BaseRequest calldata baseRequest,
// uint256[] calldata batchesAmount,
// RouterPath[][] calldata batches,
// PMMSwapRequest[] calldata extraData,
// address to
// ) external payable;
function uniswapV3SwapTo(
uint256 receiver,
uint256 amount,
uint256 minReturn,
uint256[] calldata pools
) external payable returns (uint256 returnAmount);
function smartSwapTo(
uint256 orderId,
address receiver,
BaseRequest calldata baseRequest,
uint256[] calldata batchesAmount,
RouterPath[][] calldata batches,
PMMSwapRequest[] calldata extraData
) external payable;
function unxswapTo(
uint256 srcToken,
uint256 amount,
uint256 minReturn,
address receiver,
// solhint-disable-next-line no-unused-vars
bytes32[] calldata pools
) external payable returns (uint256 returnAmount);
function unxswapByOrderId(
uint256 srcToken,
uint256 amount,
uint256 minReturn,
// solhint-disable-next-line no-unused-vars
bytes32[] calldata pools
) external payable returns (uint256 returnAmount);
function smartSwapByOrderId(
uint256 orderId,
BaseRequest calldata baseRequest,
uint256[] calldata batchesAmount,
RouterPath[][] calldata batches,
PMMSwapRequest[] calldata extraData
) external payable returns (uint256 returnAmount);
}
contracts/pendle/contracts/router/swap-aggregator/ParaswapScaleHelper.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IAugustusV6 {
// ============ Generic Swap ============
struct GenericData {
IERC20 srcToken;
IERC20 destToken;
uint256 fromAmount;
uint256 toAmount;
uint256 quotedAmount;
bytes32 metadata;
address payable beneficiary;
}
function swapExactAmountIn(
address executor,
GenericData calldata swapData,
uint256 partnerAndFee,
bytes calldata permit,
bytes calldata executorData
) external payable;
// ============ UniswapV2 Swap ============
struct UniswapV2Data {
IERC20 srcToken;
IERC20 destToken;
uint256 fromAmount;
uint256 toAmount;
uint256 quotedAmount;
bytes32 metadata;
address payable beneficiary;
bytes pools;
}
function swapExactAmountInOnUniswapV2(
UniswapV2Data calldata uniData,
uint256 partnerAndFee,
bytes calldata permit
) external payable returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
// ============ UniswapV3 Swap ============
struct UniswapV3Data {
IERC20 srcToken;
IERC20 destToken;
uint256 fromAmount;
uint256 toAmount;
uint256 quotedAmount;
bytes32 metadata;
address payable beneficiary;
bytes pools;
}
function swapExactAmountInOnUniswapV3(
UniswapV3Data calldata uniData,
uint256 partnerAndFee,
bytes calldata permit
) external payable returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
// ============ BalancerV2 Swap ============
struct BalancerV2Data {
uint256 fromAmount;
uint256 toAmount;
uint256 quotedAmount;
bytes32 metadata;
uint256 beneficiaryAndApproveFlag;
}
function swapExactAmountInOnBalancerV2(
BalancerV2Data calldata balancerData,
uint256 partnerAndFee,
bytes calldata permit,
bytes calldata data
) external payable returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
// ============ CurveV1 Swap ============
struct CurveV1Data {
uint256 curveData;
uint256 curveAssets;
IERC20 srcToken;
IERC20 destToken;
uint256 fromAmount;
uint256 toAmount;
uint256 quotedAmount;
bytes32 metadata;
address payable beneficiary;
}
function swapExactAmountInOnCurveV1(
CurveV1Data calldata curveV1Data,
uint256 partnerAndFee,
bytes calldata permit
) external payable returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
// ============ CurveV2 Swap ============
struct CurveV2Data {
uint256 curveData;
uint256 i;
uint256 j;
address poolAddress;
IERC20 srcToken;
IERC20 destToken;
uint256 fromAmount;
uint256 toAmount;
uint256 quotedAmount;
bytes32 metadata;
address payable beneficiary;
}
function swapExactAmountInOnCurveV2(
CurveV2Data calldata curveV2Data,
uint256 partnerAndFee,
bytes calldata permit
) external payable returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
// ============ MakerPSM Swap ============
struct MakerPSMData {
IERC20 srcToken;
IERC20 destToken;
uint256 fromAmount;
uint256 toAmount;
uint256 toll;
uint256 to18ConversionFactor;
address exchange;
address gemJoinAddress;
bytes32 metadata;
uint256 beneficiaryDirectionApproveFlag;
}
function swapExactAmountInOutOnMakerPSM(
MakerPSMData calldata makerPSMData,
bytes calldata permit
) external returns (uint256 spentAmount, uint256 receivedAmount);
}
contract ParaswapScaleHelper {
function _paraswapScaling(
bytes calldata rawCallData,
uint256 amountIn
) internal pure returns (bytes memory scaledCallData) {
bytes4 selector = bytes4(rawCallData[:4]);
bytes calldata dataToDecode = rawCallData[4:];
// Handle Generic Swap
if (selector == IAugustusV6.swapExactAmountIn.selector) {
(
address executor,
IAugustusV6.GenericData memory swapData,
uint256 partnerAndFee,
bytes memory permit,
bytes memory executorData
) = abi.decode(dataToDecode, (address, IAugustusV6.GenericData, uint256, bytes, bytes));
// Direct scaling calculation
swapData.toAmount = (swapData.toAmount * amountIn) / swapData.fromAmount;
swapData.quotedAmount = (swapData.quotedAmount * amountIn) / swapData.fromAmount;
swapData.fromAmount = amountIn;
return abi.encodeWithSelector(selector, executor, swapData, partnerAndFee, permit, executorData);
}
// Handle UniswapV2
else if (selector == IAugustusV6.swapExactAmountInOnUniswapV2.selector) {
(IAugustusV6.UniswapV2Data memory uniData, uint256 partnerAndFee, bytes memory permit) = abi.decode(
dataToDecode,
(IAugustusV6.UniswapV2Data, uint256, bytes)
);
// Direct scaling calculation
uniData.toAmount = (uniData.toAmount * amountIn) / uniData.fromAmount;
uniData.quotedAmount = (uniData.quotedAmount * amountIn) / uniData.fromAmount;
uniData.fromAmount = amountIn;
return abi.encodeWithSelector(selector, uniData, partnerAndFee, permit);
}
// Handle UniswapV3
else if (selector == IAugustusV6.swapExactAmountInOnUniswapV3.selector) {
(IAugustusV6.UniswapV3Data memory uniV3Data, uint256 partnerAndFee, bytes memory permit) = abi.decode(
dataToDecode,
(IAugustusV6.UniswapV3Data, uint256, bytes)
);
// Direct scaling calculation
uniV3Data.toAmount = (uniV3Data.toAmount * amountIn) / uniV3Data.fromAmount;
uniV3Data.quotedAmount = (uniV3Data.quotedAmount * amountIn) / uniV3Data.fromAmount;
uniV3Data.fromAmount = amountIn;
return abi.encodeWithSelector(selector, uniV3Data, partnerAndFee, permit);
}
// Handle BalancerV2
else if (selector == IAugustusV6.swapExactAmountInOnBalancerV2.selector) {
(
IAugustusV6.BalancerV2Data memory balancerData,
uint256 partnerAndFee,
bytes memory permit,
bytes memory data
) = abi.decode(dataToDecode, (IAugustusV6.BalancerV2Data, uint256, bytes, bytes));
// Direct scaling calculation
balancerData.toAmount = (balancerData.toAmount * amountIn) / balancerData.fromAmount;
balancerData.quotedAmount = (balancerData.quotedAmount * amountIn) / balancerData.fromAmount;
balancerData.fromAmount = amountIn;
return abi.encodeWithSelector(selector, balancerData, partnerAndFee, permit, data);
}
// Handle CurveV1
else if (selector == IAugustusV6.swapExactAmountInOnCurveV1.selector) {
(IAugustusV6.CurveV1Data memory curveV1Data, uint256 partnerAndFee, bytes memory permit) = abi.decode(
dataToDecode,
(IAugustusV6.CurveV1Data, uint256, bytes)
);
// Direct scaling calculation
curveV1Data.toAmount = (curveV1Data.toAmount * amountIn) / curveV1Data.fromAmount;
curveV1Data.quotedAmount = (curveV1Data.quotedAmount * amountIn) / curveV1Data.fromAmount;
curveV1Data.fromAmount = amountIn;
return abi.encodeWithSelector(selector, curveV1Data, partnerAndFee, permit);
}
// Handle CurveV2
else if (selector == IAugustusV6.swapExactAmountInOnCurveV2.selector) {
(IAugustusV6.CurveV2Data memory curveV2Data, uint256 partnerAndFee, bytes memory permit) = abi.decode(
dataToDecode,
(IAugustusV6.CurveV2Data, uint256, bytes)
);
// Direct scaling calculation
curveV2Data.toAmount = (curveV2Data.toAmount * amountIn) / curveV2Data.fromAmount;
curveV2Data.quotedAmount = (curveV2Data.quotedAmount * amountIn) / curveV2Data.fromAmount;
curveV2Data.fromAmount = amountIn;
return abi.encodeWithSelector(selector, curveV2Data, partnerAndFee, permit);
}
// Handle MakerPSM
else if (selector == IAugustusV6.swapExactAmountInOutOnMakerPSM.selector) {
(IAugustusV6.MakerPSMData memory makerPSMData, bytes memory permit) = abi.decode(
dataToDecode,
(IAugustusV6.MakerPSMData, bytes)
);
// Direct scaling calculation
makerPSMData.toAmount = (makerPSMData.toAmount * amountIn) / makerPSMData.fromAmount;
makerPSMData.fromAmount = amountIn;
return abi.encodeWithSelector(selector, makerPSMData, permit);
}
revert("ParaswapScaleHelper: Unsupported swap selector");
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 1000000,
"enabled": true
},
"evmVersion": "shanghai",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.