{ "language": "Solidity", "sources": { "node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n" }, "node_modules/@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n" }, "node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/draft-IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" }, "node_modules/@openzeppelin/contracts/utils/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n" }, "src/Errors/GenericErrors.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nerror AlreadyInitialized();\nerror CannotAuthoriseSelf();\nerror CannotBridgeToSameNetwork();\nerror ContractCallNotAllowed();\nerror CumulativeSlippageTooHigh(uint256 minAmount, uint256 receivedAmount);\nerror ExternalCallFailed();\nerror InformationMismatch();\nerror InsufficientBalance(uint256 required, uint256 balance);\nerror InvalidAmount();\nerror InvalidCallData();\nerror InvalidConfig();\nerror InvalidContract();\nerror InvalidDestinationChain();\nerror InvalidFallbackAddress();\nerror InvalidReceiver();\nerror InvalidSendingToken();\nerror NativeAssetNotSupported();\nerror NativeAssetTransferFailed();\nerror NoSwapDataProvided();\nerror NoSwapFromZeroBalance();\nerror NotAContract();\nerror NotInitialized();\nerror NoTransferToNullAddress();\nerror NullAddrIsNotAnERC20Token();\nerror NullAddrIsNotAValidSpender();\nerror OnlyContractOwner();\nerror RecoveryAddressCannotBeZero();\nerror ReentrancyError();\nerror TokenNotSupported();\nerror UnAuthorized();\nerror UnsupportedChainId(uint256 chainId);\nerror ZeroAmount();\n" }, "src/Helpers/ReentrancyGuard.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.17;\n\n/// @title Reentrancy Guard\n/// @author LI.FI (https://li.fi)\n/// @notice Abstract contract to provide protection against reentrancy\nabstract contract ReentrancyGuard {\n /// Storage ///\n\n bytes32 private constant NAMESPACE = keccak256(\"com.lifi.reentrancyguard\");\n\n /// Types ///\n\n struct ReentrancyStorage {\n uint256 status;\n }\n\n /// Errors ///\n\n error ReentrancyError();\n\n /// Constants ///\n\n uint256 private constant _NOT_ENTERED = 0;\n uint256 private constant _ENTERED = 1;\n\n /// Modifiers ///\n\n modifier nonReentrant() {\n ReentrancyStorage storage s = reentrancyStorage();\n if (s.status == _ENTERED) revert ReentrancyError();\n s.status = _ENTERED;\n _;\n s.status = _NOT_ENTERED;\n }\n\n /// Private Methods ///\n\n /// @dev fetch local storage\n function reentrancyStorage()\n private\n pure\n returns (ReentrancyStorage storage data)\n {\n bytes32 position = NAMESPACE;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n data.slot := position\n }\n }\n}\n" }, "src/Helpers/TransferrableOwnership.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { IERC173 } from \"../Interfaces/IERC173.sol\";\nimport { LibAsset } from \"../Libraries/LibAsset.sol\";\n\ncontract TransferrableOwnership is IERC173 {\n address public owner;\n address public pendingOwner;\n\n /// Errors ///\n error UnAuthorized();\n error NoNullOwner();\n error NewOwnerMustNotBeSelf();\n error NoPendingOwnershipTransfer();\n error NotPendingOwner();\n\n /// Events ///\n event OwnershipTransferRequested(\n address indexed _from,\n address indexed _to\n );\n\n constructor(address initialOwner) {\n owner = initialOwner;\n }\n\n modifier onlyOwner() {\n if (msg.sender != owner) revert UnAuthorized();\n _;\n }\n\n /// @notice Initiates transfer of ownership to a new address\n /// @param _newOwner the address to transfer ownership to\n function transferOwnership(address _newOwner) external onlyOwner {\n if (_newOwner == LibAsset.NULL_ADDRESS) revert NoNullOwner();\n if (_newOwner == msg.sender) revert NewOwnerMustNotBeSelf();\n pendingOwner = _newOwner;\n emit OwnershipTransferRequested(msg.sender, pendingOwner);\n }\n\n /// @notice Cancel transfer of ownership\n function cancelOwnershipTransfer() external onlyOwner {\n if (pendingOwner == LibAsset.NULL_ADDRESS)\n revert NoPendingOwnershipTransfer();\n pendingOwner = LibAsset.NULL_ADDRESS;\n }\n\n /// @notice Confirms transfer of ownership to the calling address (msg.sender)\n function confirmOwnershipTransfer() external {\n address _pendingOwner = pendingOwner;\n if (msg.sender != _pendingOwner) revert NotPendingOwner();\n emit OwnershipTransferred(owner, _pendingOwner);\n owner = _pendingOwner;\n pendingOwner = LibAsset.NULL_ADDRESS;\n }\n}\n" }, "src/Interfaces/IERC173.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/// @title ERC-173 Contract Ownership Standard\n/// Note: the ERC-165 identifier for this interface is 0x7f5828d0\n/* is ERC165 */\ninterface IERC173 {\n /// @dev This emits when ownership of a contract changes.\n event OwnershipTransferred(\n address indexed previousOwner,\n address indexed newOwner\n );\n\n /// @notice Get the address of the owner\n /// @return owner_ The address of the owner.\n function owner() external view returns (address owner_);\n\n /// @notice Set the address of the new owner of the contract\n /// @dev Set _newOwner to address(0) to renounce any ownership.\n /// @param _newOwner The address of the new owner of the contract\n function transferOwnership(address _newOwner) external;\n}\n" }, "src/Interfaces/IExecutor.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { LibSwap } from \"../Libraries/LibSwap.sol\";\n\n/// @title Interface for Executor\n/// @author LI.FI (https://li.fi)\ninterface IExecutor {\n /// @notice Performs a swap before completing a cross-chain transaction\n /// @param _transactionId the transaction id associated with the operation\n /// @param _swapData array of data needed for swaps\n /// @param transferredAssetId token received from the other chain\n /// @param receiver address that will receive tokens in the end\n function swapAndCompleteBridgeTokens(\n bytes32 _transactionId,\n LibSwap.SwapData[] calldata _swapData,\n address transferredAssetId,\n address payable receiver\n ) external payable;\n}\n" }, "src/Interfaces/ILiFi.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\ninterface ILiFi {\n /// Structs ///\n\n struct BridgeData {\n bytes32 transactionId;\n string bridge;\n string integrator;\n address referrer;\n address sendingAssetId;\n address receiver;\n uint256 minAmount;\n uint256 destinationChainId;\n bool hasSourceSwaps;\n bool hasDestinationCall;\n }\n\n /// Events ///\n\n event LiFiTransferStarted(ILiFi.BridgeData bridgeData);\n\n event LiFiTransferCompleted(\n bytes32 indexed transactionId,\n address receivingAssetId,\n address receiver,\n uint256 amount,\n uint256 timestamp\n );\n\n event LiFiTransferRecovered(\n bytes32 indexed transactionId,\n address receivingAssetId,\n address receiver,\n uint256 amount,\n uint256 timestamp\n );\n}\n" }, "src/Libraries/LibAsset.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.17;\nimport { InsufficientBalance, NullAddrIsNotAnERC20Token, NullAddrIsNotAValidSpender, NoTransferToNullAddress, InvalidAmount, NativeAssetTransferFailed } from \"../Errors/GenericErrors.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { LibSwap } from \"./LibSwap.sol\";\n\n/// @title LibAsset\n/// @notice This library contains helpers for dealing with onchain transfers\n/// of assets, including accounting for the native asset `assetId`\n/// conventions and any noncompliant ERC20 transfers\nlibrary LibAsset {\n uint256 private constant MAX_UINT = type(uint256).max;\n\n address internal constant NULL_ADDRESS = address(0);\n\n /// @dev All native assets use the empty address for their asset id\n /// by convention\n\n address internal constant NATIVE_ASSETID = NULL_ADDRESS; //address(0)\n\n /// @notice Gets the balance of the inheriting contract for the given asset\n /// @param assetId The asset identifier to get the balance of\n /// @return Balance held by contracts using this library\n function getOwnBalance(address assetId) internal view returns (uint256) {\n return\n assetId == NATIVE_ASSETID\n ? address(this).balance\n : IERC20(assetId).balanceOf(address(this));\n }\n\n /// @notice Transfers ether from the inheriting contract to a given\n /// recipient\n /// @param recipient Address to send ether to\n /// @param amount Amount to send to given recipient\n function transferNativeAsset(address payable recipient, uint256 amount)\n private\n {\n if (recipient == NULL_ADDRESS) revert NoTransferToNullAddress();\n if (amount > address(this).balance)\n revert InsufficientBalance(amount, address(this).balance);\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, ) = recipient.call{ value: amount }(\"\");\n if (!success) revert NativeAssetTransferFailed();\n }\n\n /// @notice If the current allowance is insufficient, the allowance for a given spender\n /// is set to MAX_UINT.\n /// @param assetId Token address to transfer\n /// @param spender Address to give spend approval to\n /// @param amount Amount to approve for spending\n function maxApproveERC20(\n IERC20 assetId,\n address spender,\n uint256 amount\n ) internal {\n if (address(assetId) == NATIVE_ASSETID) return;\n if (spender == NULL_ADDRESS) revert NullAddrIsNotAValidSpender();\n uint256 allowance = assetId.allowance(address(this), spender);\n\n if (allowance < amount)\n SafeERC20.safeIncreaseAllowance(\n IERC20(assetId),\n spender,\n MAX_UINT - allowance\n );\n }\n\n /// @notice Transfers tokens from the inheriting contract to a given\n /// recipient\n /// @param assetId Token address to transfer\n /// @param recipient Address to send token to\n /// @param amount Amount to send to given recipient\n function transferERC20(\n address assetId,\n address recipient,\n uint256 amount\n ) private {\n if (isNativeAsset(assetId)) revert NullAddrIsNotAnERC20Token();\n uint256 assetBalance = IERC20(assetId).balanceOf(address(this));\n if (amount > assetBalance)\n revert InsufficientBalance(amount, assetBalance);\n SafeERC20.safeTransfer(IERC20(assetId), recipient, amount);\n }\n\n /// @notice Transfers tokens from a sender to a given recipient\n /// @param assetId Token address to transfer\n /// @param from Address of sender/owner\n /// @param to Address of recipient/spender\n /// @param amount Amount to transfer from owner to spender\n function transferFromERC20(\n address assetId,\n address from,\n address to,\n uint256 amount\n ) internal {\n if (assetId == NATIVE_ASSETID) revert NullAddrIsNotAnERC20Token();\n if (to == NULL_ADDRESS) revert NoTransferToNullAddress();\n\n IERC20 asset = IERC20(assetId);\n uint256 prevBalance = asset.balanceOf(to);\n SafeERC20.safeTransferFrom(asset, from, to, amount);\n if (asset.balanceOf(to) - prevBalance != amount)\n revert InvalidAmount();\n }\n\n function depositAsset(address assetId, uint256 amount) internal {\n if (isNativeAsset(assetId)) {\n if (msg.value < amount) revert InvalidAmount();\n } else {\n if (amount == 0) revert InvalidAmount();\n uint256 balance = IERC20(assetId).balanceOf(msg.sender);\n if (balance < amount) revert InsufficientBalance(amount, balance);\n transferFromERC20(assetId, msg.sender, address(this), amount);\n }\n }\n\n function depositAssets(LibSwap.SwapData[] calldata swaps) internal {\n for (uint256 i = 0; i < swaps.length; ) {\n LibSwap.SwapData memory swap = swaps[i];\n if (swap.requiresDeposit) {\n depositAsset(swap.sendingAssetId, swap.fromAmount);\n }\n unchecked {\n i++;\n }\n }\n }\n\n /// @notice Determines whether the given assetId is the native asset\n /// @param assetId The asset identifier to evaluate\n /// @return Boolean indicating if the asset is the native asset\n function isNativeAsset(address assetId) internal pure returns (bool) {\n return assetId == NATIVE_ASSETID;\n }\n\n /// @notice Wrapper function to transfer a given asset (native or erc20) to\n /// some recipient. Should handle all non-compliant return value\n /// tokens as well by using the SafeERC20 contract by open zeppelin.\n /// @param assetId Asset id for transfer (address(0) for native asset,\n /// token address for erc20s)\n /// @param recipient Address to send asset to\n /// @param amount Amount to send to given recipient\n function transferAsset(\n address assetId,\n address payable recipient,\n uint256 amount\n ) internal {\n (assetId == NATIVE_ASSETID)\n ? transferNativeAsset(recipient, amount)\n : transferERC20(assetId, recipient, amount);\n }\n\n /// @dev Checks whether the given address is a contract and contains code\n function isContract(address _contractAddr) internal view returns (bool) {\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n size := extcodesize(_contractAddr)\n }\n return size > 0;\n }\n}\n" }, "src/Libraries/LibBytes.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nlibrary LibBytes {\n // solhint-disable no-inline-assembly\n\n // LibBytes specific errors\n error SliceOverflow();\n error SliceOutOfBounds();\n error AddressOutOfBounds();\n error UintOutOfBounds();\n\n // -------------------------\n\n function concat(bytes memory _preBytes, bytes memory _postBytes)\n internal\n pure\n returns (bytes memory)\n {\n bytes memory tempBytes;\n\n assembly {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // Store the length of the first bytes array at the beginning of\n // the memory for tempBytes.\n let length := mload(_preBytes)\n mstore(tempBytes, length)\n\n // Maintain a memory counter for the current write location in the\n // temp bytes array by adding the 32 bytes for the array length to\n // the starting location.\n let mc := add(tempBytes, 0x20)\n // Stop copying when the memory counter reaches the length of the\n // first bytes array.\n let end := add(mc, length)\n\n for {\n // Initialize a copy counter to the start of the _preBytes data,\n // 32 bytes into its memory.\n let cc := add(_preBytes, 0x20)\n } lt(mc, end) {\n // Increase both counters by 32 bytes each iteration.\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // Write the _preBytes data into the tempBytes memory 32 bytes\n // at a time.\n mstore(mc, mload(cc))\n }\n\n // Add the length of _postBytes to the current length of tempBytes\n // and store it as the new length in the first 32 bytes of the\n // tempBytes memory.\n length := mload(_postBytes)\n mstore(tempBytes, add(length, mload(tempBytes)))\n\n // Move the memory counter back from a multiple of 0x20 to the\n // actual end of the _preBytes data.\n mc := end\n // Stop copying when the memory counter reaches the new combined\n // length of the arrays.\n end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n // Update the free-memory pointer by padding our last write location\n // to 32 bytes: add 31 bytes to the end of tempBytes to move to the\n // next 32 byte block, then round down to the nearest multiple of\n // 32. If the sum of the length of the two arrays is zero then add\n // one before rounding down to leave a blank 32 bytes (the length block with 0).\n mstore(\n 0x40,\n and(\n add(add(end, iszero(add(length, mload(_preBytes)))), 31),\n not(31) // Round down to the nearest 32 bytes.\n )\n )\n }\n\n return tempBytes;\n }\n\n function concatStorage(bytes storage _preBytes, bytes memory _postBytes)\n internal\n {\n assembly {\n // Read the first 32 bytes of _preBytes storage, which is the length\n // of the array. (We don't need to use the offset into the slot\n // because arrays use the entire slot.)\n let fslot := sload(_preBytes.slot)\n // Arrays of 31 bytes or less have an even value in their slot,\n // while longer arrays have an odd value. The actual length is\n // the slot divided by two for odd values, and the lowest order\n // byte divided by two for even values.\n // If the slot is even, bitwise and the slot with 255 and divide by\n // two to get the length. If the slot is odd, bitwise and the slot\n // with -1 and divide by two.\n let slength := div(\n and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)),\n 2\n )\n let mlength := mload(_postBytes)\n let newlength := add(slength, mlength)\n // slength can contain both the length and contents of the array\n // if length < 32 bytes so let's prepare for that\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n switch add(lt(slength, 32), lt(newlength, 32))\n case 2 {\n // Since the new array still fits in the slot, we just need to\n // update the contents of the slot.\n // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length\n sstore(\n _preBytes.slot,\n // all the modifications to the slot are inside this\n // next block\n add(\n // we can just add to the slot contents because the\n // bytes we want to change are the LSBs\n fslot,\n add(\n mul(\n div(\n // load the bytes from memory\n mload(add(_postBytes, 0x20)),\n // zero all bytes to the right\n exp(0x100, sub(32, mlength))\n ),\n // and now shift left the number of bytes to\n // leave space for the length in the slot\n exp(0x100, sub(32, newlength))\n ),\n // increase length by the double of the memory\n // bytes length\n mul(mlength, 2)\n )\n )\n )\n }\n case 1 {\n // The stored value fits in the slot, but the combined value\n // will exceed it.\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n // save new length\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n // The contents of the _postBytes array start 32 bytes into\n // the structure. Our first read should obtain the `submod`\n // bytes that can fit into the unused space in the last word\n // of the stored array. To get this, we read 32 bytes starting\n // from `submod`, so the data we read overlaps with the array\n // contents by `submod` bytes. Masking the lowest-order\n // `submod` bytes allows us to add that value directly to the\n // stored value.\n\n let submod := sub(32, slength)\n let mc := add(_postBytes, submod)\n let end := add(_postBytes, mlength)\n let mask := sub(exp(0x100, submod), 1)\n\n sstore(\n sc,\n add(\n and(\n fslot,\n 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00\n ),\n and(mload(mc), mask)\n )\n )\n\n for {\n mc := add(mc, 0x20)\n sc := add(sc, 1)\n } lt(mc, end) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n sstore(sc, mload(mc))\n }\n\n mask := exp(0x100, sub(mc, end))\n\n sstore(sc, mul(div(mload(mc), mask), mask))\n }\n default {\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n // Start copying to the last used word of the stored array.\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n // save new length\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n // Copy over the first `submod` bytes of the new data as in\n // case 1 above.\n let slengthmod := mod(slength, 32)\n let submod := sub(32, slengthmod)\n let mc := add(_postBytes, submod)\n let end := add(_postBytes, mlength)\n let mask := sub(exp(0x100, submod), 1)\n\n sstore(sc, add(sload(sc), and(mload(mc), mask)))\n\n for {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } lt(mc, end) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n sstore(sc, mload(mc))\n }\n\n mask := exp(0x100, sub(mc, end))\n\n sstore(sc, mul(div(mload(mc), mask), mask))\n }\n }\n }\n\n function slice(\n bytes memory _bytes,\n uint256 _start,\n uint256 _length\n ) internal pure returns (bytes memory) {\n if (_length + 31 < _length) revert SliceOverflow();\n if (_bytes.length < _start + _length) revert SliceOutOfBounds();\n\n bytes memory tempBytes;\n\n assembly {\n switch iszero(_length)\n case 0 {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // The first word of the slice result is potentially a partial\n // word read from the original array. To read it, we calculate\n // the length of that partial word and start copying that many\n // bytes into the array. The first word we copy will start with\n // data we don't care about, but the last `lengthmod` bytes will\n // land at the beginning of the contents of the new array. When\n // we're done copying, we overwrite the full first word with\n // the actual length of the slice.\n let lengthmod := and(_length, 31)\n\n // The multiplication in the next line is necessary\n // because when slicing multiples of 32 bytes (lengthmod == 0)\n // the following copy loop was copying the origin's length\n // and then ending prematurely not copying everything it should.\n let mc := add(\n add(tempBytes, lengthmod),\n mul(0x20, iszero(lengthmod))\n )\n let end := add(mc, _length)\n\n for {\n // The multiplication in the next line has the same exact purpose\n // as the one above.\n let cc := add(\n add(\n add(_bytes, lengthmod),\n mul(0x20, iszero(lengthmod))\n ),\n _start\n )\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n mstore(tempBytes, _length)\n\n //update free-memory pointer\n //allocating the array padded to 32 bytes like the compiler does now\n mstore(0x40, and(add(mc, 31), not(31)))\n }\n //if we want a zero-length slice let's just return a zero-length array\n default {\n tempBytes := mload(0x40)\n //zero out the 32 bytes slice we are about to return\n //we need to do it because Solidity does not garbage collect\n mstore(tempBytes, 0)\n\n mstore(0x40, add(tempBytes, 0x20))\n }\n }\n\n return tempBytes;\n }\n\n function toAddress(bytes memory _bytes, uint256 _start)\n internal\n pure\n returns (address)\n {\n if (_bytes.length < _start + 20) {\n revert AddressOutOfBounds();\n }\n address tempAddress;\n\n assembly {\n tempAddress := div(\n mload(add(add(_bytes, 0x20), _start)),\n 0x1000000000000000000000000\n )\n }\n\n return tempAddress;\n }\n\n function toUint8(bytes memory _bytes, uint256 _start)\n internal\n pure\n returns (uint8)\n {\n if (_bytes.length < _start + 1) {\n revert UintOutOfBounds();\n }\n uint8 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x1), _start))\n }\n\n return tempUint;\n }\n\n function toUint16(bytes memory _bytes, uint256 _start)\n internal\n pure\n returns (uint16)\n {\n if (_bytes.length < _start + 2) {\n revert UintOutOfBounds();\n }\n uint16 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x2), _start))\n }\n\n return tempUint;\n }\n\n function toUint32(bytes memory _bytes, uint256 _start)\n internal\n pure\n returns (uint32)\n {\n if (_bytes.length < _start + 4) {\n revert UintOutOfBounds();\n }\n uint32 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x4), _start))\n }\n\n return tempUint;\n }\n\n function toUint64(bytes memory _bytes, uint256 _start)\n internal\n pure\n returns (uint64)\n {\n if (_bytes.length < _start + 8) {\n revert UintOutOfBounds();\n }\n uint64 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x8), _start))\n }\n\n return tempUint;\n }\n\n function toUint96(bytes memory _bytes, uint256 _start)\n internal\n pure\n returns (uint96)\n {\n if (_bytes.length < _start + 12) {\n revert UintOutOfBounds();\n }\n uint96 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0xc), _start))\n }\n\n return tempUint;\n }\n\n function toUint128(bytes memory _bytes, uint256 _start)\n internal\n pure\n returns (uint128)\n {\n if (_bytes.length < _start + 16) {\n revert UintOutOfBounds();\n }\n uint128 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x10), _start))\n }\n\n return tempUint;\n }\n\n function toUint256(bytes memory _bytes, uint256 _start)\n internal\n pure\n returns (uint256)\n {\n if (_bytes.length < _start + 32) {\n revert UintOutOfBounds();\n }\n uint256 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x20), _start))\n }\n\n return tempUint;\n }\n\n function toBytes32(bytes memory _bytes, uint256 _start)\n internal\n pure\n returns (bytes32)\n {\n if (_bytes.length < _start + 32) {\n revert UintOutOfBounds();\n }\n bytes32 tempBytes32;\n\n assembly {\n tempBytes32 := mload(add(add(_bytes, 0x20), _start))\n }\n\n return tempBytes32;\n }\n\n function equal(bytes memory _preBytes, bytes memory _postBytes)\n internal\n pure\n returns (bool)\n {\n bool success = true;\n\n assembly {\n let length := mload(_preBytes)\n\n // if lengths don't match the arrays are not equal\n switch eq(length, mload(_postBytes))\n case 1 {\n // cb is a circuit breaker in the for loop since there's\n // no said feature for inline assembly loops\n // cb = 1 - don't breaker\n // cb = 0 - break\n let cb := 1\n\n let mc := add(_preBytes, 0x20)\n let end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n // the next line is the loop condition:\n // while(uint256(mc < end) + cb == 2)\n } eq(add(lt(mc, end), cb), 2) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // if any of these checks fails then arrays are not equal\n if iszero(eq(mload(mc), mload(cc))) {\n // unsuccess:\n success := 0\n cb := 0\n }\n }\n }\n default {\n // unsuccess:\n success := 0\n }\n }\n\n return success;\n }\n\n function equalStorage(bytes storage _preBytes, bytes memory _postBytes)\n internal\n view\n returns (bool)\n {\n bool success = true;\n\n assembly {\n // we know _preBytes_offset is 0\n let fslot := sload(_preBytes.slot)\n // Decode the length of the stored array like in concatStorage().\n let slength := div(\n and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)),\n 2\n )\n let mlength := mload(_postBytes)\n\n // if lengths don't match the arrays are not equal\n switch eq(slength, mlength)\n case 1 {\n // slength can contain both the length and contents of the array\n // if length < 32 bytes so let's prepare for that\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n if iszero(iszero(slength)) {\n switch lt(slength, 32)\n case 1 {\n // blank the last byte which is the length\n fslot := mul(div(fslot, 0x100), 0x100)\n\n if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {\n // unsuccess:\n success := 0\n }\n }\n default {\n // cb is a circuit breaker in the for loop since there's\n // no said feature for inline assembly loops\n // cb = 1 - don't breaker\n // cb = 0 - break\n let cb := 1\n\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n let sc := keccak256(0x0, 0x20)\n\n let mc := add(_postBytes, 0x20)\n let end := add(mc, mlength)\n\n // the next line is the loop condition:\n // while(uint256(mc < end) + cb == 2)\n // solhint-disable-next-line no-empty-blocks\n for {\n\n } eq(add(lt(mc, end), cb), 2) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n if iszero(eq(sload(sc), mload(mc))) {\n // unsuccess:\n success := 0\n cb := 0\n }\n }\n }\n }\n }\n default {\n // unsuccess:\n success := 0\n }\n }\n\n return success;\n }\n}\n" }, "src/Libraries/LibSwap.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { LibAsset } from \"./LibAsset.sol\";\nimport { LibUtil } from \"./LibUtil.sol\";\nimport { InvalidContract, NoSwapFromZeroBalance, InsufficientBalance } from \"../Errors/GenericErrors.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nlibrary LibSwap {\n struct SwapData {\n address callTo;\n address approveTo;\n address sendingAssetId;\n address receivingAssetId;\n uint256 fromAmount;\n bytes callData;\n bool requiresDeposit;\n }\n\n event AssetSwapped(\n bytes32 transactionId,\n address dex,\n address fromAssetId,\n address toAssetId,\n uint256 fromAmount,\n uint256 toAmount,\n uint256 timestamp\n );\n\n function swap(bytes32 transactionId, SwapData calldata _swap) internal {\n if (!LibAsset.isContract(_swap.callTo)) revert InvalidContract();\n uint256 fromAmount = _swap.fromAmount;\n if (fromAmount == 0) revert NoSwapFromZeroBalance();\n uint256 nativeValue = LibAsset.isNativeAsset(_swap.sendingAssetId)\n ? _swap.fromAmount\n : 0;\n uint256 initialSendingAssetBalance = LibAsset.getOwnBalance(\n _swap.sendingAssetId\n );\n uint256 initialReceivingAssetBalance = LibAsset.getOwnBalance(\n _swap.receivingAssetId\n );\n\n if (nativeValue == 0) {\n LibAsset.maxApproveERC20(\n IERC20(_swap.sendingAssetId),\n _swap.approveTo,\n _swap.fromAmount\n );\n }\n\n if (initialSendingAssetBalance < _swap.fromAmount) {\n revert InsufficientBalance(\n _swap.fromAmount,\n initialSendingAssetBalance\n );\n }\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory res) = _swap.callTo.call{\n value: nativeValue\n }(_swap.callData);\n if (!success) {\n string memory reason = LibUtil.getRevertMsg(res);\n revert(reason);\n }\n\n uint256 newBalance = LibAsset.getOwnBalance(_swap.receivingAssetId);\n\n emit AssetSwapped(\n transactionId,\n _swap.callTo,\n _swap.sendingAssetId,\n _swap.receivingAssetId,\n _swap.fromAmount,\n newBalance > initialReceivingAssetBalance\n ? newBalance - initialReceivingAssetBalance\n : newBalance,\n block.timestamp\n );\n }\n}\n" }, "src/Libraries/LibUtil.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport \"./LibBytes.sol\";\n\nlibrary LibUtil {\n using LibBytes for bytes;\n\n function getRevertMsg(bytes memory _res)\n internal\n pure\n returns (string memory)\n {\n // If the _res length is less than 68, then the transaction failed silently (without a revert message)\n if (_res.length < 68) return \"Transaction reverted silently\";\n bytes memory revertData = _res.slice(4, _res.length - 4); // Remove the selector which is the first 4 bytes\n return abi.decode(revertData, (string)); // All that remains is the revert string\n }\n\n /// @notice Determines whether the given address is the zero address\n /// @param addr The address to verify\n /// @return Boolean indicating if the address is the zero address\n function isZeroAddress(address addr) internal pure returns (bool) {\n return addr == address(0);\n }\n}\n" }, "src/Periphery/Receiver.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { IERC20, SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { ReentrancyGuard } from \"../Helpers/ReentrancyGuard.sol\";\nimport { LibSwap } from \"../Libraries/LibSwap.sol\";\nimport { LibAsset } from \"../Libraries/LibAsset.sol\";\nimport { ILiFi } from \"../Interfaces/ILiFi.sol\";\nimport { IExecutor } from \"../Interfaces/IExecutor.sol\";\nimport { TransferrableOwnership } from \"../Helpers/TransferrableOwnership.sol\";\nimport { UnAuthorized } from \"../Errors/GenericErrors.sol\";\n\n/// @title Executor\n/// @author LI.FI (https://li.fi)\n/// @notice Arbitrary execution contract used for cross-chain swaps and message passing\ncontract Receiver is ILiFi, ReentrancyGuard, TransferrableOwnership {\n using SafeERC20 for IERC20;\n\n /// Storage ///\n address public sgRouter;\n IExecutor public executor;\n uint256 public recoverGas;\n address public amarokRouter;\n\n /// Errors ///\n\n /// Events ///\n event StargateRouterSet(address indexed router);\n event AmarokRouterSet(address indexed router);\n event ExecutorSet(address indexed executor);\n event RecoverGasSet(uint256 indexed recoverGas);\n\n /// Modifiers ///\n modifier onlySGRouter() {\n if (msg.sender != sgRouter) {\n revert UnAuthorized();\n }\n _;\n }\n modifier onlyAmarokRouter() {\n if (msg.sender != amarokRouter) {\n revert UnAuthorized();\n }\n _;\n }\n\n /// Constructor\n constructor(\n address _owner,\n address _sgRouter,\n address _amarokRouter,\n address _executor,\n uint256 _recoverGas\n ) TransferrableOwnership(_owner) {\n owner = _owner;\n sgRouter = _sgRouter;\n amarokRouter = _amarokRouter;\n executor = IExecutor(_executor);\n recoverGas = _recoverGas;\n emit StargateRouterSet(_sgRouter);\n emit AmarokRouterSet(_amarokRouter);\n emit RecoverGasSet(_recoverGas);\n }\n\n /// External Methods ///\n\n /// @notice set stargate router\n /// @param _sgRouter the stargate router address\n function setStargateRouter(address _sgRouter) external onlyOwner {\n sgRouter = _sgRouter;\n emit StargateRouterSet(_sgRouter);\n }\n\n /// @notice Sets the address of the Amarok router\n /// @param _amarokRouter the Amarok router address\n function setAmarokRouter(address _amarokRouter) external onlyOwner {\n amarokRouter = _amarokRouter;\n emit AmarokRouterSet(_amarokRouter);\n }\n\n /// @notice set Executor\n /// @param _executor the Executor address\n function setExecutor(address _executor) external onlyOwner {\n executor = IExecutor(_executor);\n emit ExecutorSet(_executor);\n }\n\n /// @notice set execution recoverGas\n /// @param _recoverGas recoverGas\n function setRecoverGas(uint256 _recoverGas) external onlyOwner {\n recoverGas = _recoverGas;\n emit RecoverGasSet(_recoverGas);\n }\n\n /// @notice Completes a cross-chain transaction with calldata via Amarok facet on the receiving chain.\n /// @dev This function is called from Amarok Router.\n /// @param _transferId The unique ID of this transaction (assigned by Amarok)\n /// @param _amount the amount of bridged tokens\n /// @param _asset the address of the bridged token\n /// @param * (unused) the sender of the transaction\n /// @param * (unused) the domain ID of the src chain\n /// @param _callData The data to execute\n function xReceive(\n bytes32 _transferId,\n uint256 _amount,\n address _asset,\n address,\n uint32,\n bytes memory _callData\n ) external nonReentrant onlyAmarokRouter {\n (LibSwap.SwapData[] memory swapData, address receiver) = abi.decode(\n _callData,\n (LibSwap.SwapData[], address)\n );\n\n _swapAndCompleteBridgeTokens(\n _transferId,\n swapData,\n _asset,\n payable(receiver),\n _amount,\n false\n );\n }\n\n /// @notice Completes a cross-chain transaction on the receiving chain.\n /// @dev This function is called from Stargate Router.\n /// @param * (unused) The remote chainId sending the tokens\n /// @param * (unused) The remote Bridge address\n /// @param * (unused) Nonce\n /// @param * (unused) The token contract on the local chain\n /// @param _amountLD The amount of tokens received through bridging\n /// @param _payload The data to execute\n function sgReceive(\n uint16, // _srcChainId unused\n bytes memory, // _srcAddress unused\n uint256, // _nonce unused\n address _token,\n uint256 _amountLD,\n bytes memory _payload\n ) external nonReentrant onlySGRouter {\n (\n bytes32 transactionId,\n LibSwap.SwapData[] memory swapData,\n ,\n address receiver\n ) = abi.decode(\n _payload,\n (bytes32, LibSwap.SwapData[], address, address)\n );\n\n _swapAndCompleteBridgeTokens(\n transactionId,\n swapData,\n _token,\n payable(receiver),\n _amountLD,\n true\n );\n }\n\n /// @notice Performs a swap before completing a cross-chain transaction\n /// @param _transactionId the transaction id associated with the operation\n /// @param _swapData array of data needed for swaps\n /// @param assetId token received from the other chain\n /// @param receiver address that will receive tokens in the end\n function swapAndCompleteBridgeTokens(\n bytes32 _transactionId,\n LibSwap.SwapData[] memory _swapData,\n address assetId,\n address payable receiver\n ) external payable nonReentrant {\n if (LibAsset.isNativeAsset(assetId)) {\n _swapAndCompleteBridgeTokens(\n _transactionId,\n _swapData,\n assetId,\n receiver,\n msg.value,\n false\n );\n } else {\n uint256 allowance = IERC20(assetId).allowance(\n msg.sender,\n address(this)\n );\n LibAsset.depositAsset(assetId, allowance);\n _swapAndCompleteBridgeTokens(\n _transactionId,\n _swapData,\n assetId,\n receiver,\n allowance,\n false\n );\n }\n }\n\n /// @notice Send remaining token to receiver\n /// @param assetId token received from the other chain\n /// @param receiver address that will receive tokens in the end\n /// @param amount amount of token\n function pullToken(\n address assetId,\n address payable receiver,\n uint256 amount\n ) external onlyOwner {\n if (LibAsset.isNativeAsset(assetId)) {\n receiver.call{ value: amount }(\"\");\n } else {\n IERC20(assetId).safeTransfer(receiver, amount);\n }\n }\n\n /// Private Methods ///\n\n /// @notice Performs a swap before completing a cross-chain transaction\n /// @param _transactionId the transaction id associated with the operation\n /// @param _swapData array of data needed for swaps\n /// @param assetId token received from the other chain\n /// @param receiver address that will receive tokens in the end\n /// @param amount amount of token\n /// @param reserveRecoverGas whether we need a gas buffer to recover\n function _swapAndCompleteBridgeTokens(\n bytes32 _transactionId,\n LibSwap.SwapData[] memory _swapData,\n address assetId,\n address payable receiver,\n uint256 amount,\n bool reserveRecoverGas\n ) private {\n uint256 _recoverGas = reserveRecoverGas ? recoverGas : 0;\n\n if (LibAsset.isNativeAsset(assetId)) {\n // case 1: native asset\n if (reserveRecoverGas && gasleft() < _recoverGas) {\n // case 1a: not enough gas left to execute calls\n receiver.call{ value: amount }(\"\");\n\n emit LiFiTransferRecovered(\n _transactionId,\n assetId,\n receiver,\n amount,\n block.timestamp\n );\n return;\n }\n\n // case 1b: enough gas left to execute calls\n try\n executor.swapAndCompleteBridgeTokens{\n value: amount,\n gas: gasleft() - _recoverGas\n }(_transactionId, _swapData, assetId, receiver)\n {} catch {\n receiver.call{ value: amount }(\"\");\n }\n } else {\n // case 2: ERC20 asset\n IERC20 token = IERC20(assetId);\n token.safeApprove(address(executor), 0);\n token.safeIncreaseAllowance(address(executor), amount);\n\n if (reserveRecoverGas && gasleft() < _recoverGas) {\n // case 2a: not enough gas left to execute calls\n token.safeTransfer(receiver, amount);\n\n emit LiFiTransferRecovered(\n _transactionId,\n assetId,\n receiver,\n amount,\n block.timestamp\n );\n return;\n }\n\n // case 2b: enough gas left to execute calls\n try\n executor.swapAndCompleteBridgeTokens{\n gas: gasleft() - _recoverGas\n }(_transactionId, _swapData, assetId, receiver)\n {} catch {\n token.safeTransfer(receiver, amount);\n emit LiFiTransferRecovered(\n _transactionId,\n assetId,\n receiver,\n amount,\n block.timestamp\n );\n }\n\n token.safeApprove(address(executor), 0);\n }\n }\n\n /// @notice Receive native asset directly.\n /// @dev Some bridges may send native asset before execute external calls.\n // solhint-disable-next-line no-empty-blocks\n receive() external payable {}\n}\n" } }, "settings": { "remappings": [ "@axelar-network/=node_modules/@axelar-network/", "@connext/=node_modules/@connext/", "@eth-optimism/=node_modules/@hop-protocol/sdk/node_modules/@eth-optimism/", "@openzeppelin/=node_modules/@openzeppelin/", "@uniswap/=node_modules/@uniswap/", "celer-network/=lib/sgn-v2-contracts/", "create3-factory/=lib/create3-factory/src/", "ds-test/=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/", "lifi/=src/", "sgn-v2-contracts/=lib/sgn-v2-contracts/contracts/", "solmate/=lib/solmate/src/", "test/=test/" ], "optimizer": { "enabled": true, "runs": 1000000 }, "metadata": { "bytecodeHash": "ipfs" }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "london", "libraries": {} } }