// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.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
* ====
*
* [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://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason 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 {
// 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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import {IDefaultPool, IDefaultExtendedPool} from "../interfaces/IDefaultExtendedPool.sol";
import {IRouterAdapter} from "../interfaces/IRouterAdapter.sol";
import {IWETH9} from "../interfaces/IWETH9.sol";
import {MsgValueIncorrect, PoolNotFound, TokenAddressMismatch, TokensIdentical} from "../libs/Errors.sol";
import {Action, DefaultParams} from "../libs/Structs.sol";
import {UniversalTokenLib} from "../libs/UniversalToken.sol";
import {SafeERC20, IERC20} from "@openzeppelin/contracts-4.5.0/token/ERC20/utils/SafeERC20.sol";
contract DefaultAdapter is IRouterAdapter {
using SafeERC20 for IERC20;
using UniversalTokenLib for address;
/// @notice Enable this contract to receive Ether when withdrawing from WETH.
/// @dev Consider implementing rescue functions to withdraw Ether from this contract.
receive() external payable {}
/// @inheritdoc IRouterAdapter
function adapterSwap(
address recipient,
address tokenIn,
uint256 amountIn,
address tokenOut,
bytes memory rawParams
) external payable returns (uint256 amountOut) {
return _adapterSwap(recipient, tokenIn, amountIn, tokenOut, rawParams);
}
/// @dev Internal logic for doing a tokenIn -> tokenOut swap.
/// Note: `tokenIn` is assumed to have already been transferred to this contract.
function _adapterSwap(
address recipient,
address tokenIn,
uint256 amountIn,
address tokenOut,
bytes memory rawParams
) internal virtual returns (uint256 amountOut) {
// We define a few phases for the whole Adapter's swap process.
// (?) means the phase is optional.
// (!) means the phase is mandatory.
// PHASE 0(!): CHECK ALL THE PARAMS
DefaultParams memory params = _checkParams(tokenIn, tokenOut, rawParams);
// PHASE 1(?): WRAP RECEIVED ETH INTO WETH
tokenIn = _wrapReceivedETH(tokenIn, amountIn, tokenOut, params);
// After PHASE 1 this contract has `amountIn` worth of `tokenIn`, tokenIn != ETH_ADDRESS
// PHASE 2(?): PREPARE TO UNWRAP SWAPPED WETH
address tokenSwapTo = _deriveTokenSwapTo(tokenIn, tokenOut, params);
// We need to perform tokenIn -> tokenSwapTo action in PHASE 3.
// if tokenOut == ETH_ADDRESS, we need to unwrap WETH in PHASE 4.
// Recipient will receive `tokenOut` in PHASE 5.
// PHASE 3(?): PERFORM A REQUESTED SWAP
amountOut = _performPoolAction(tokenIn, amountIn, tokenSwapTo, params);
// After PHASE 3 this contract has `amountOut` worth of `tokenSwapTo`, tokenSwapTo != ETH_ADDRESS
// PHASE 4(?): UNWRAP SWAPPED WETH
// Check if the final token is native ETH
if (tokenOut == UniversalTokenLib.ETH_ADDRESS) {
// PHASE 2: WETH address was stored as `tokenSwapTo`
_unwrapETH(tokenSwapTo, amountOut);
}
// PHASE 5(!): TRANSFER SWAPPED TOKENS TO RECIPIENT
// Note: this will transfer native ETH, if tokenOut == ETH_ADDRESS
// Note: this is a no-op if recipient == address(this)
tokenOut.universalTransfer(recipient, amountOut);
}
/// @dev Checks the params and decodes them into a struct.
function _checkParams(
address tokenIn,
address tokenOut,
bytes memory rawParams
) internal pure returns (DefaultParams memory params) {
if (tokenIn == tokenOut) revert TokensIdentical();
// Decode params for swapping via a Default pool
params = abi.decode(rawParams, (DefaultParams));
// Swap pool should exist, if action other than HandleEth was requested
if (params.pool == address(0) && params.action != Action.HandleEth) revert PoolNotFound();
}
/// @dev Wraps native ETH into WETH, if requested.
/// Returns the address of the token this contract ends up with.
function _wrapReceivedETH(
address tokenIn,
uint256 amountIn,
address tokenOut,
DefaultParams memory params
) internal returns (address wrappedTokenIn) {
// tokenIn was already transferred to this contract, check if we start from native ETH
if (tokenIn == UniversalTokenLib.ETH_ADDRESS) {
// Determine WETH address: this is either tokenOut (if no swap is needed),
// or a pool token with index `tokenIndexFrom` (if swap is needed).
wrappedTokenIn = _deriveWethAddress({token: tokenOut, params: params, isTokenFromWeth: true});
// Wrap ETH into WETH and leave it in this contract
_wrapETH(wrappedTokenIn, amountIn);
} else {
wrappedTokenIn = tokenIn;
// For ERC20 tokens msg.value should be zero
if (msg.value != 0) revert MsgValueIncorrect();
}
}
/// @dev Derives the address of token to be received after an action defined in `params`.
function _deriveTokenSwapTo(
address tokenIn,
address tokenOut,
DefaultParams memory params
) internal view returns (address tokenSwapTo) {
// Check if swap to native ETH was requested
if (tokenOut == UniversalTokenLib.ETH_ADDRESS) {
// Determine WETH address: this is either tokenIn (if no swap is needed),
// or a pool token with index `tokenIndexTo` (if swap is needed).
tokenSwapTo = _deriveWethAddress({token: tokenIn, params: params, isTokenFromWeth: false});
} else {
tokenSwapTo = tokenOut;
}
}
/// @dev Performs an action defined in `params` and returns the amount of `tokenSwapTo` received.
function _performPoolAction(
address tokenIn,
uint256 amountIn,
address tokenSwapTo,
DefaultParams memory params
) internal returns (uint256 amountOut) {
// Determine if we need to perform a swap
if (params.action == Action.HandleEth) {
// If no swap is required, amountOut doesn't change
amountOut = amountIn;
} else {
// Record balance before the swap
amountOut = IERC20(tokenSwapTo).balanceOf(address(this));
// Approve the pool for spending exactly `amountIn` of `tokenIn`
IERC20(tokenIn).safeIncreaseAllowance(params.pool, amountIn);
if (params.action == Action.Swap) {
_swap(params.pool, params, amountIn, tokenSwapTo);
} else if (params.action == Action.AddLiquidity) {
_addLiquidity(params.pool, params, amountIn, tokenSwapTo);
} else {
// The only remaining action is RemoveLiquidity
_removeLiquidity(params.pool, params, amountIn, tokenSwapTo);
}
// Use the difference between the balance after the swap and the recorded balance as `amountOut`
amountOut = IERC20(tokenSwapTo).balanceOf(address(this)) - amountOut;
}
}
// ═══════════════════════════════════════ INTERNAL LOGIC: SWAP ACTIONS ════════════════════════════════════════════
/// @dev Performs a swap through the given pool.
/// Note: The pool should be already approved for spending `tokenIn`.
function _swap(
address pool,
DefaultParams memory params,
uint256 amountIn,
address tokenOut
) internal {
// tokenOut should match the "swap to" token
if (IDefaultPool(pool).getToken(params.tokenIndexTo) != tokenOut) revert TokenAddressMismatch();
// amountOut and deadline are not checked in RouterAdapter
IDefaultPool(pool).swap({
tokenIndexFrom: params.tokenIndexFrom,
tokenIndexTo: params.tokenIndexTo,
dx: amountIn,
minDy: 0,
deadline: type(uint256).max
});
}
/// @dev Adds liquidity in a form of a single token to the given pool.
/// Note: The pool should be already approved for spending `tokenIn`.
function _addLiquidity(
address pool,
DefaultParams memory params,
uint256 amountIn,
address tokenOut
) internal {
uint256 numTokens = _getPoolNumTokens(pool);
address lpToken = _getPoolLPToken(pool);
// tokenOut should match the LP token
if (lpToken != tokenOut) revert TokenAddressMismatch();
uint256[] memory amounts = new uint256[](numTokens);
amounts[params.tokenIndexFrom] = amountIn;
// amountOut and deadline are not checked in RouterAdapter
IDefaultExtendedPool(pool).addLiquidity({amounts: amounts, minToMint: 0, deadline: type(uint256).max});
}
/// @dev Removes liquidity in a form of a single token from the given pool.
/// Note: The pool should be already approved for spending `tokenIn`.
function _removeLiquidity(
address pool,
DefaultParams memory params,
uint256 amountIn,
address tokenOut
) internal {
// tokenOut should match the "swap to" token
if (IDefaultPool(pool).getToken(params.tokenIndexTo) != tokenOut) revert TokenAddressMismatch();
// amountOut and deadline are not checked in RouterAdapter
IDefaultExtendedPool(pool).removeLiquidityOneToken({
tokenAmount: amountIn,
tokenIndex: params.tokenIndexTo,
minAmount: 0,
deadline: type(uint256).max
});
}
// ═════════════════════════════════════════ INTERNAL LOGIC: POOL LENS ═════════════════════════════════════════════
/// @dev Returns the LP token address of the given pool.
function _getPoolLPToken(address pool) internal view returns (address lpToken) {
(, , , , , , lpToken) = IDefaultExtendedPool(pool).swapStorage();
}
/// @dev Returns the number of tokens in the given pool.
function _getPoolNumTokens(address pool) internal view returns (uint256 numTokens) {
// Iterate over all tokens in the pool until the end is reached
for (uint8 index = 0; ; ++index) {
try IDefaultPool(pool).getToken(index) returns (address) {} catch {
// End of pool reached
numTokens = index;
break;
}
}
}
/// @dev Returns the tokens in the given pool.
function _getPoolTokens(address pool) internal view returns (address[] memory tokens) {
uint256 numTokens = _getPoolNumTokens(pool);
tokens = new address[](numTokens);
for (uint8 i = 0; i < numTokens; ++i) {
// This will not revert because we already know the number of tokens in the pool
tokens[i] = IDefaultPool(pool).getToken(i);
}
}
/// @dev Returns the quote for a swap through the given pool.
/// Note: will return 0 on invalid swaps.
function _getPoolSwapQuote(
address pool,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 amountIn
) internal view returns (uint256 amountOut) {
try IDefaultPool(pool).calculateSwap(tokenIndexFrom, tokenIndexTo, amountIn) returns (uint256 dy) {
amountOut = dy;
} catch {
// Return 0 instead of reverting
amountOut = 0;
}
}
// ════════════════════════════════════════ INTERNAL LOGIC: ETH <> WETH ════════════════════════════════════════════
/// @dev Wraps ETH into WETH.
function _wrapETH(address weth, uint256 amount) internal {
if (amount != msg.value) revert MsgValueIncorrect();
// Deposit in order to have WETH in this contract
IWETH9(weth).deposit{value: amount}();
}
/// @dev Unwraps WETH into ETH.
function _unwrapETH(address weth, uint256 amount) internal {
// Withdraw ETH to this contract
IWETH9(weth).withdraw(amount);
}
/// @dev Derives WETH address from swap parameters.
function _deriveWethAddress(
address token,
DefaultParams memory params,
bool isTokenFromWeth
) internal view returns (address weth) {
if (params.action == Action.HandleEth) {
// If we only need to wrap/unwrap ETH, WETH address should be specified as the other token
weth = token;
} else {
// Otherwise, we need to get WETH address from the liquidity pool
weth = address(
IDefaultPool(params.pool).getToken(isTokenFromWeth ? params.tokenIndexFrom : params.tokenIndexTo)
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import {DefaultAdapter} from "./adapters/DefaultAdapter.sol";
import {IRouterAdapter} from "./interfaces/IRouterAdapter.sol";
import {DeadlineExceeded, InsufficientOutputAmount, MsgValueIncorrect, TokenNotETH} from "./libs/Errors.sol";
import {Action, DefaultParams, SwapQuery} from "./libs/Structs.sol";
import {UniversalTokenLib} from "./libs/UniversalToken.sol";
import {SafeERC20, IERC20} from "@openzeppelin/contracts-4.5.0/token/ERC20/utils/SafeERC20.sol";
/// @title DefaultRouter
/// @notice Base contract for all Synapse Routers, that is able to natively work with Default Pools
/// due to the fact that it inherits from DefaultAdapter.
abstract contract DefaultRouter is DefaultAdapter {
using SafeERC20 for IERC20;
using UniversalTokenLib for address;
/// @dev Performs a "swap from tokenIn" following instructions from `query`.
/// `query` will include the router adapter to use, and the exact type of "tokenIn -> tokenOut swap"
/// should be encoded in `query.rawParams`.
function _doSwap(
address recipient,
address tokenIn,
uint256 amountIn,
SwapQuery memory query
) internal returns (address tokenOut, uint256 amountOut) {
// First, check the deadline for the swap
// solhint-disable-next-line not-rely-on-time
if (block.timestamp > query.deadline) revert DeadlineExceeded();
// Pull initial token from the user to specified router adapter
amountIn = _pullToken(query.routerAdapter, tokenIn, amountIn);
tokenOut = query.tokenOut;
address routerAdapter = query.routerAdapter;
if (routerAdapter == address(this)) {
// If the router adapter is this contract, we can perform the swap directly and trust the result
amountOut = _adapterSwap(recipient, tokenIn, amountIn, tokenOut, query.rawParams);
} else {
// Otherwise, we need to call the router adapter. Adapters are permissionless, so we verify the result
// Record tokenOut balance before swap
amountOut = tokenOut.universalBalanceOf(recipient);
IRouterAdapter(routerAdapter).adapterSwap{value: msg.value}({
recipient: recipient,
tokenIn: tokenIn,
amountIn: amountIn,
tokenOut: tokenOut,
rawParams: query.rawParams
});
// Use the difference between the recorded balance and the current balance as the amountOut
amountOut = tokenOut.universalBalanceOf(recipient) - amountOut;
}
// Finally, check that the recipient received at least as much as they wanted
if (amountOut < query.minAmountOut) revert InsufficientOutputAmount();
}
/// @dev Pulls a requested token from the user to the requested recipient.
/// Or, if msg.value was provided, check that ETH_ADDRESS was used and msg.value is correct.
function _pullToken(
address recipient,
address token,
uint256 amount
) internal returns (uint256 amountPulled) {
if (msg.value == 0) {
token.assertIsContract();
// Record token balance before transfer
amountPulled = IERC20(token).balanceOf(recipient);
// Token needs to be pulled only if msg.value is zero
// This way user can specify WETH as the origin asset
IERC20(token).safeTransferFrom(msg.sender, recipient, amount);
// Use the difference between the recorded balance and the current balance as the amountPulled
amountPulled = IERC20(token).balanceOf(recipient) - amountPulled;
} else {
// Otherwise, we need to check that ETH was specified
if (token != UniversalTokenLib.ETH_ADDRESS) revert TokenNotETH();
// And that amount matches msg.value
if (amount != msg.value) revert MsgValueIncorrect();
// We will forward msg.value in the external call later, if recipient is not this contract
amountPulled = msg.value;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
error DeadlineExceeded();
error InsufficientOutputAmount();
error MsgValueIncorrect();
error PoolNotFound();
error TokenAddressMismatch();
error TokenNotContract();
error TokenNotETH();
error TokensIdentical();
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import {DefaultRouter, DeadlineExceeded, InsufficientOutputAmount} from "../router/DefaultRouter.sol";
import {UniversalTokenLib} from "../router/libs/UniversalToken.sol";
import {ActionLib, LimitedToken} from "../router/libs/Structs.sol";
import {IFastBridge} from "./interfaces/IFastBridge.sol";
import {IFastBridgeRouter, SwapQuery} from "./interfaces/IFastBridgeRouter.sol";
import {ISwapQuoter} from "./interfaces/ISwapQuoter.sol";
import {Ownable} from "@openzeppelin/contracts-4.5.0/access/Ownable.sol";
contract FastBridgeRouterV2 is DefaultRouter, Ownable, IFastBridgeRouter {
using UniversalTokenLib for address;
error FastBridgeRouterV2__OriginSenderNotSpecified();
/// @notice Emitted when the swap quoter is set.
/// @param newSwapQuoter The new swap quoter.
event SwapQuoterSet(address newSwapQuoter);
/// @notice Emitted when the new FastBridge contract is set.
/// @param newFastBridge The new FastBridge contract.
event FastBridgeSet(address newFastBridge);
/// @inheritdoc IFastBridgeRouter
bytes1 public constant GAS_REBATE_FLAG = 0x2A;
/// @inheritdoc IFastBridgeRouter
address public fastBridge;
/// @inheritdoc IFastBridgeRouter
address public swapQuoter;
constructor(address owner_) {
transferOwnership(owner_);
}
/// @inheritdoc IFastBridgeRouter
function setFastBridge(address fastBridge_) external onlyOwner {
fastBridge = fastBridge_;
emit FastBridgeSet(fastBridge_);
}
/// @inheritdoc IFastBridgeRouter
function setSwapQuoter(address swapQuoter_) external onlyOwner {
swapQuoter = swapQuoter_;
emit SwapQuoterSet(swapQuoter_);
}
/// @inheritdoc IFastBridgeRouter
function bridge(
address recipient,
uint256 chainId,
address token,
uint256 amount,
SwapQuery memory originQuery,
SwapQuery memory destQuery
) external payable {
address originSender = _getOriginSender(destQuery.rawParams);
if (originSender == address(0)) {
revert FastBridgeRouterV2__OriginSenderNotSpecified();
}
if (originQuery.hasAdapter()) {
// Perform a swap using the swap adapter, set this contract as recipient
(token, amount) = _doSwap(address(this), token, amount, originQuery);
} else {
// Otherwise, pull the token from the user to this contract
// We still need to perform the deadline and amountOut checks
// solhint-disable-next-line not-rely-on-time
if (block.timestamp > originQuery.deadline) {
revert DeadlineExceeded();
}
if (amount < originQuery.minAmountOut) {
revert InsufficientOutputAmount();
}
amount = _pullToken(address(this), token, amount);
}
IFastBridge.BridgeParams memory params = IFastBridge.BridgeParams({
dstChainId: uint32(chainId),
sender: originSender,
to: recipient,
originToken: token,
destToken: destQuery.tokenOut,
originAmount: amount,
destAmount: destQuery.minAmountOut,
sendChainGas: _chainGasRequested(destQuery.rawParams),
deadline: destQuery.deadline
});
token.universalApproveInfinity(fastBridge, amount);
uint256 msgValue = token == UniversalTokenLib.ETH_ADDRESS ? amount : 0;
IFastBridge(fastBridge).bridge{value: msgValue}(params);
}
/// @inheritdoc IFastBridgeRouter
function getOriginAmountOut(
address tokenIn,
address[] memory rfqTokens,
uint256 amountIn
) external view returns (SwapQuery[] memory originQueries) {
uint256 len = rfqTokens.length;
originQueries = new SwapQuery[](len);
for (uint256 i = 0; i < len; ++i) {
originQueries[i] = ISwapQuoter(swapQuoter).getAmountOut(
LimitedToken({actionMask: ActionLib.allActions(), token: tokenIn}),
rfqTokens[i],
amountIn
);
// Adjust the Adapter address if it exists
if (originQueries[i].hasAdapter()) {
originQueries[i].routerAdapter = address(this);
}
}
}
/// @dev Retrieves the origin sender from the raw params.
/// Note: falls back to msg.sender if origin sender is not specified in the raw params, but
/// msg.sender is an EOA.
function _getOriginSender(bytes memory rawParams) internal view returns (address originSender) {
// Origin sender (if present) is encoded as 20 bytes following the rebate flag
if (rawParams.length >= 21) {
// The easiest way to read from memory is to use assembly
// solhint-disable-next-line no-inline-assembly
assembly {
// Skip the rawParams.length (32 bytes) and the rebate flag (1 byte)
originSender := mload(add(rawParams, 33))
// The address is in the highest 160 bits. Shift right by 96 to get it in the lowest 160 bits
originSender := shr(96, originSender)
}
}
if (originSender == address(0) && msg.sender.code.length == 0) {
// Fall back to msg.sender if it is an EOA. This maintains backward compatibility
// for cases where we can safely assume that the origin sender is the same as msg.sender.
originSender = msg.sender;
}
}
/// @dev Checks if the explicit instruction to send gas to the destination chain was provided.
function _chainGasRequested(bytes memory rawParams) internal pure returns (bool) {
return rawParams.length > 0 && rawParams[0] == GAS_REBATE_FLAG;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import {IDefaultPool} from "./IDefaultPool.sol";
interface IDefaultExtendedPool is IDefaultPool {
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external returns (uint256);
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
) external returns (uint256);
// ═══════════════════════════════════════════════════ VIEWS ═══════════════════════════════════════════════════════
function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory);
function calculateRemoveLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex)
external
view
returns (uint256 availableTokenAmount);
function getAPrecise() external view returns (uint256);
function getTokenBalance(uint8 index) external view returns (uint256);
function swapStorage()
external
view
returns (
uint256 initialA,
uint256 futureA,
uint256 initialATime,
uint256 futureATime,
uint256 swapFee,
uint256 adminFee,
address lpToken
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
interface IDefaultPool {
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
) external returns (uint256 amountOut);
function calculateSwap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256 amountOut);
function getToken(uint8 index) external view returns (address token);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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);
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// TODO: This should be pulled from the sanguine repo (requires publish and relaxing the ^0.8.20 pragma)
interface IFastBridge {
struct BridgeTransaction {
uint32 originChainId;
uint32 destChainId;
address originSender; // user (origin)
address destRecipient; // user (dest)
address originToken;
address destToken;
uint256 originAmount; // amount in on origin bridge less originFeeAmount
uint256 destAmount;
uint256 originFeeAmount;
bool sendChainGas;
uint256 deadline;
uint256 nonce;
}
struct BridgeProof {
uint96 timestamp;
address relayer;
}
// ============ Events ============
event BridgeRequested(bytes32 transactionId, address sender, bytes request);
event BridgeRelayed(
bytes32 transactionId,
address relayer,
address to,
address token,
uint256 amount,
uint256 chainGasAmount
);
event BridgeProofProvided(bytes32 transactionId, address relayer, bytes32 transactionHash);
event BridgeProofDisputed(bytes32 transactionId, address relayer);
event BridgeDepositClaimed(bytes32 transactionId, address relayer, address to, address token, uint256 amount);
event BridgeDepositRefunded(bytes32 transactionId, address to, address token, uint256 amount);
// ============ Methods ============
struct BridgeParams {
uint32 dstChainId;
address sender;
address to;
address originToken;
address destToken;
uint256 originAmount; // should include protocol fee (if any)
uint256 destAmount; // should include relayer fee
bool sendChainGas;
uint256 deadline;
}
/// @notice Initiates bridge on origin chain to be relayed by off-chain relayer
/// @param params The parameters required to bridge
function bridge(BridgeParams memory params) external payable;
/// @notice Relays destination side of bridge transaction by off-chain relayer
/// @param request The encoded bridge transaction to relay on destination chain
function relay(bytes memory request) external payable;
/// @notice Provides proof on origin side that relayer provided funds on destination side of bridge transaction
/// @param request The encoded bridge transaction to prove on origin chain
/// @param destTxHash The destination tx hash proving bridge transaction was relayed
function prove(bytes memory request, bytes32 destTxHash) external;
/// @notice Completes bridge transaction on origin chain by claiming originally deposited capital
/// @param request The encoded bridge transaction to claim on origin chain
/// @param to The recipient address of the funds
function claim(bytes memory request, address to) external;
/// @notice Disputes an outstanding proof in case relayer provided dest chain tx is invalid
/// @param transactionId The transaction id associated with the encoded bridge transaction to dispute
function dispute(bytes32 transactionId) external;
/// @notice Refunds an outstanding bridge transaction in case optimistic bridging failed
/// @param request The encoded bridge transaction to refund
/// @param to The recipient address of the funds
function refund(bytes memory request, address to) external;
// ============ Views ============
/// @notice Decodes bridge request into a bridge transaction
/// @param request The bridge request to decode
function getBridgeTransaction(bytes memory request) external pure returns (BridgeTransaction memory);
/// @notice Checks if the dispute period has passed so bridge deposit can be claimed
/// @param transactionId The transaction id associated with the encoded bridge transaction to check
/// @param relayer The address of the relayer attempting to claim
function canClaim(bytes32 transactionId, address relayer) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SwapQuery} from "../../router/libs/Structs.sol";
interface IFastBridgeRouter {
/// @notice Sets the address of the FastBridge contract
/// @dev This function is only callable by the owner
/// @param fastBridge_ The address of the FastBridge contract
function setFastBridge(address fastBridge_) external;
/// @notice Sets the address of the SwapQuoter contract
/// @dev This function is only callable by the owner
/// @param swapQuoter_ The address of the SwapQuoter contract
function setSwapQuoter(address swapQuoter_) external;
/// @notice Initiate an RFQ transaction with an optional swap on origin chain,
/// and an optional gas rebate on destination chain.
/// @dev Note that method is payable.
/// If token is ETH_ADDRESS, this method should be invoked with `msg.value = amountIn`.
/// If token is ERC20, the tokens will be pulled from msg.sender (use `msg.value = 0`).
/// Make sure to approve this contract for spending `token` beforehand.
///
/// `originQuery` is supposed to be fetched using FastBridgeRouter.getOriginAmountOut().
/// Alternatively one could use an external adapter for more complex swaps on the origin chain.
/// `destQuery.rawParams` signals whether the user wants to receive a gas rebate on the destination chain:
/// - If the first byte of `destQuery.rawParams` is GAS_REBATE_FLAG, the user wants to receive a gas rebate.
/// - Otherwise, the user does not want to receive a gas rebate.
///
/// Cross-chain RFQ swap will be performed between tokens: `originQuery.tokenOut` and `destQuery.tokenOut`.
/// Note: both tokens could be ETH_ADDRESS or ERC20.
/// Full proceeds of the origin swap are considered the bid for the cross-chain swap.
/// `destQuery.minAmountOut` is considered the ask for the cross-chain swap.
/// Note: applying slippage to `destQuery.minAmountOut` will result in a worse price for the user,
/// the full Relayer quote should be used instead.
/// @param recipient Address to receive tokens on destination chain
/// @param chainId Destination chain id
/// @param token Initial token to be pulled from the user
/// @param amount Amount of the initial tokens to be pulled from the user
/// @param originQuery Origin swap query (see above)
/// @param destQuery Destination swap query (see above)
function bridge(
address recipient,
uint256 chainId,
address token,
uint256 amount,
SwapQuery memory originQuery,
SwapQuery memory destQuery
) external payable;
// ═══════════════════════════════════════════════════ VIEWS ═══════════════════════════════════════════════════════
/// @notice Finds the best path between `tokenIn` and every RFQ token from the given list,
/// treating the swap as "origin swap", without putting any restrictions on the swap.
/// @dev Check (query.minAmountOut != 0): this is true only if the swap is possible.
/// The returned queries with minAmountOut != 0 could be used as `originQuery` with FastBridgeRouter.
/// Note: it is possible to form a SwapQuery off-chain using alternative SwapAdapter for the origin swap.
/// @param tokenIn Initial token that user wants to bridge/swap
/// @param rfqTokens List of RFQ tokens
/// @param amountIn Amount of tokens user wants to bridge/swap
/// @return originQueries List of structs that could be used as `originQuery` in FastBridgeRouter.
/// minAmountOut and deadline fields will need to be adjusted based on the user settings.
function getOriginAmountOut(
address tokenIn,
address[] memory rfqTokens,
uint256 amountIn
) external view returns (SwapQuery[] memory originQueries);
/// @notice Magic value that indicates that the user wants to receive gas rebate on the destination chain.
/// This is the answer to the ultimate question of life, the universe, and everything.
function GAS_REBATE_FLAG() external view returns (bytes1);
/// @notice Address of the FastBridge contract, used to initiate cross-chain RFQ swaps.
function fastBridge() external view returns (address);
/// @notice Address of the SwapQuoter contract, used to fetch quotes for the origin swap.
function swapQuoter() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
interface IRouterAdapter {
/// @notice Performs a tokenIn -> tokenOut swap, according to the provided params.
/// If tokenIn is ETH_ADDRESS, this method should be invoked with `msg.value = amountIn`.
/// If tokenIn is ERC20, the tokens should be already transferred to this contract (using `msg.value = 0`).
/// If tokenOut is ETH_ADDRESS, native ETH will be sent to the recipient (be aware of potential reentrancy).
/// If tokenOut is ERC20, the tokens will be transferred to the recipient.
/// @dev Contracts implementing {IRouterAdapter} interface are required to enforce the above restrictions.
/// On top of that, they must ensure that exactly `amountOut` worth of `tokenOut` is transferred to the recipient.
/// Swap deadline and slippage is checked outside of this contract.
/// @param recipient Address to receive the swapped token
/// @param tokenIn Token to sell (use ETH_ADDRESS to start from native ETH)
/// @param amountIn Amount of tokens to sell
/// @param tokenOut Token to buy (use ETH_ADDRESS to end with native ETH)
/// @param rawParams Additional swap parameters
/// @return amountOut Amount of bought tokens
function adapterSwap(
address recipient,
address tokenIn,
uint256 amountIn,
address tokenOut,
bytes calldata rawParams
) external payable returns (uint256 amountOut);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {LimitedToken, SwapQuery} from "../../router/libs/Structs.sol";
interface ISwapQuoter {
function getAmountOut(
LimitedToken memory tokenIn,
address tokenOut,
uint256 amountIn
) external view returns (SwapQuery memory query);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
interface IWETH9 {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.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;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
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));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
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");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @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");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13; // "using A for B global" requires 0.8.13 or higher
// ══════════════════════════════════════════ TOKEN AND POOL DESCRIPTION ═══════════════════════════════════════════════
/// @notice Struct representing a bridge token. Used as the return value in view functions.
/// @param symbol Bridge token symbol: unique token ID consistent among all chains
/// @param token Bridge token address
struct BridgeToken {
string symbol;
address token;
}
/// @notice Struct used by IPoolHandler to represent a token in a pool
/// @param index Token index in the pool
/// @param token Token address
struct IndexedToken {
uint8 index;
address token;
}
/// @notice Struct representing a token, and the available Actions for performing a swap.
/// @param actionMask Bitmask representing what actions (see ActionLib) are available for swapping a token
/// @param token Token address
struct LimitedToken {
uint256 actionMask;
address token;
}
/// @notice Struct representing how pool tokens are stored by `SwapQuoter`.
/// @param isWeth Whether the token represents Wrapped ETH.
/// @param token Token address.
struct PoolToken {
bool isWeth;
address token;
}
/// @notice Struct representing a liquidity pool. Used as the return value in view functions.
/// @param pool Pool address.
/// @param lpToken Address of pool's LP token.
/// @param tokens List of pool's tokens.
struct Pool {
address pool;
address lpToken;
PoolToken[] tokens;
}
// ════════════════════════════════════════════════ ROUTER STRUCTS ═════════════════════════════════════════════════════
/// @notice Struct representing a quote request for swapping a bridge token.
/// Used in destination chain's SynapseRouter, hence the name "Destination Request".
/// @dev tokenOut is passed externally.
/// @param symbol Bridge token symbol: unique token ID consistent among all chains
/// @param amountIn Amount of bridge token to start with, before the bridge fee is applied
struct DestRequest {
string symbol;
uint256 amountIn;
}
/// @notice Struct representing a swap request for SynapseRouter.
/// @dev tokenIn is supplied separately.
/// @param routerAdapter Contract that will perform the swap for the Router. Address(0) specifies a "no swap" query.
/// @param tokenOut Token address to swap to.
/// @param minAmountOut Minimum amount of tokens to receive after the swap, or tx will be reverted.
/// @param deadline Latest timestamp for when the transaction needs to be executed, or tx will be reverted.
/// @param rawParams ABI-encoded params for the swap that will be passed to `routerAdapter`.
/// Should be DefaultParams for swaps via DefaultAdapter.
struct SwapQuery {
address routerAdapter;
address tokenOut;
uint256 minAmountOut;
uint256 deadline;
bytes rawParams;
}
using SwapQueryLib for SwapQuery global;
library SwapQueryLib {
/// @notice Checks whether the router adapter was specified in the query.
/// Query without a router adapter specifies that no action needs to be taken.
function hasAdapter(SwapQuery memory query) internal pure returns (bool) {
return query.routerAdapter != address(0);
}
/// @notice Fills `routerAdapter` and `deadline` fields in query, if it specifies one of the supported Actions,
/// and if a path for this action was found.
function fillAdapterAndDeadline(SwapQuery memory query, address routerAdapter) internal pure {
// Fill the fields only if some path was found.
if (query.minAmountOut == 0) return;
// Empty params indicates no action needs to be done, thus no adapter is needed.
query.routerAdapter = query.rawParams.length == 0 ? address(0) : routerAdapter;
// Set default deadline to infinity. Not using the value of 0,
// which would lead to every swap to revert by default.
query.deadline = type(uint256).max;
}
}
// ════════════════════════════════════════════════ ADAPTER STRUCTS ════════════════════════════════════════════════════
/// @notice Struct representing parameters for swapping via DefaultAdapter.
/// @param action Action that DefaultAdapter needs to perform.
/// @param pool Liquidity pool that will be used for Swap/AddLiquidity/RemoveLiquidity actions.
/// @param tokenIndexFrom Token index to swap from. Used for swap/addLiquidity actions.
/// @param tokenIndexTo Token index to swap to. Used for swap/removeLiquidity actions.
struct DefaultParams {
Action action;
address pool;
uint8 tokenIndexFrom;
uint8 tokenIndexTo;
}
/// @notice All possible actions that DefaultAdapter could perform.
enum Action {
Swap, // swap between two pools tokens
AddLiquidity, // add liquidity in a form of a single pool token
RemoveLiquidity, // remove liquidity in a form of a single pool token
HandleEth // ETH <> WETH interaction
}
using ActionLib for Action global;
/// @notice Library for dealing with bit masks which describe what set of Actions is available.
library ActionLib {
/// @notice Returns a bitmask with all possible actions set to True.
function allActions() internal pure returns (uint256 actionMask) {
actionMask = type(uint256).max;
}
/// @notice Returns whether the given action is set to True in the bitmask.
function isIncluded(Action action, uint256 actionMask) internal pure returns (bool) {
return actionMask & mask(action) != 0;
}
/// @notice Returns a bitmask with only the given action set to True.
function mask(Action action) internal pure returns (uint256) {
return 1 << uint256(action);
}
/// @notice Returns a bitmask with only two given actions set to True.
function mask(Action a, Action b) internal pure returns (uint256) {
return mask(a) | mask(b);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import {TokenNotContract} from "./Errors.sol";
import {SafeERC20, IERC20} from "@openzeppelin/contracts-4.5.0/token/ERC20/utils/SafeERC20.sol";
library UniversalTokenLib {
using SafeERC20 for IERC20;
address internal constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Transfers tokens to the given account. Reverts if transfer is not successful.
/// @dev This might trigger fallback, if ETH is transferred to the contract.
/// Make sure this can not lead to reentrancy attacks.
function universalTransfer(
address token,
address to,
uint256 value
) internal {
// Don't do anything, if need to send tokens to this address
if (to == address(this)) return;
if (token == ETH_ADDRESS) {
/// @dev Note: this can potentially lead to executing code in `to`.
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = to.call{value: value}("");
require(success, "ETH transfer failed");
} else {
IERC20(token).safeTransfer(to, value);
}
}
/// @notice Issues an infinite allowance to the spender, if the current allowance is insufficient
/// to spend the given amount.
function universalApproveInfinity(
address token,
address spender,
uint256 amountToSpend
) internal {
// ETH Chad doesn't require your approval
if (token == ETH_ADDRESS) return;
// No-op if allowance is already sufficient
uint256 allowance = IERC20(token).allowance(address(this), spender);
if (allowance >= amountToSpend) return;
// Otherwise, reset approval to 0 and set to max allowance
if (allowance > 0) IERC20(token).safeApprove(spender, 0);
IERC20(token).safeApprove(spender, type(uint256).max);
}
/// @notice Returns the balance of the given token (or native ETH) for the given account.
function universalBalanceOf(address token, address account) internal view returns (uint256) {
if (token == ETH_ADDRESS) {
return account.balance;
} else {
return IERC20(token).balanceOf(account);
}
}
/// @dev Checks that token is a contract and not ETH_ADDRESS.
function assertIsContract(address token) internal view {
// Check that ETH_ADDRESS was not used (in case this is a predeploy on any of the chains)
if (token == UniversalTokenLib.ETH_ADDRESS) revert TokenNotContract();
// Check that token is not an EOA
if (token.code.length == 0) revert TokenNotContract();
}
}
{
"compilationTarget": {
"contracts/rfq/FastBridgeRouterV2.sol": "FastBridgeRouterV2"
},
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [
":@boringcrypto/=node_modules/@boringcrypto/",
":@ensdomains/=node_modules/@ensdomains/",
":@openzeppelin/=node_modules/@openzeppelin/",
":ds-test/=lib/forge-std/lib/ds-test/src/",
":eth-gas-reporter/=node_modules/eth-gas-reporter/",
":forge-std/=lib/forge-std/src/",
":hardhat-deploy/=node_modules/hardhat-deploy/",
":hardhat/=node_modules/hardhat/",
":sol-explore/=node_modules/sol-explore/",
":solmate/=lib/solmate/src/",
":synthetix/=node_modules/synthetix/"
]
}
[{"inputs":[{"internalType":"address","name":"owner_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"DeadlineExceeded","type":"error"},{"inputs":[],"name":"FastBridgeRouterV2__OriginSenderNotSpecified","type":"error"},{"inputs":[],"name":"InsufficientOutputAmount","type":"error"},{"inputs":[],"name":"MsgValueIncorrect","type":"error"},{"inputs":[],"name":"PoolNotFound","type":"error"},{"inputs":[],"name":"TokenAddressMismatch","type":"error"},{"inputs":[],"name":"TokenNotContract","type":"error"},{"inputs":[],"name":"TokenNotETH","type":"error"},{"inputs":[],"name":"TokensIdentical","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newFastBridge","type":"address"}],"name":"FastBridgeSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newSwapQuoter","type":"address"}],"name":"SwapQuoterSet","type":"event"},{"inputs":[],"name":"GAS_REBATE_FLAG","outputs":[{"internalType":"bytes1","name":"","type":"bytes1"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"bytes","name":"rawParams","type":"bytes"}],"name":"adapterSwap","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"components":[{"internalType":"address","name":"routerAdapter","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bytes","name":"rawParams","type":"bytes"}],"internalType":"struct SwapQuery","name":"originQuery","type":"tuple"},{"components":[{"internalType":"address","name":"routerAdapter","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bytes","name":"rawParams","type":"bytes"}],"internalType":"struct SwapQuery","name":"destQuery","type":"tuple"}],"name":"bridge","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"fastBridge","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address[]","name":"rfqTokens","type":"address[]"},{"internalType":"uint256","name":"amountIn","type":"uint256"}],"name":"getOriginAmountOut","outputs":[{"components":[{"internalType":"address","name":"routerAdapter","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bytes","name":"rawParams","type":"bytes"}],"internalType":"struct SwapQuery[]","name":"originQueries","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"fastBridge_","type":"address"}],"name":"setFastBridge","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"swapQuoter_","type":"address"}],"name":"setSwapQuoter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"swapQuoter","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]