Overview
ETH Balance
ETH Value
$0.00More Info
Private Name Tags
ContractCreator
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Latest 1 internal transaction
Parent Transaction Hash | Block | From | To | |||
---|---|---|---|---|---|---|
474133 | 510 days ago | Contract Creation | 0 ETH |
Loading...
Loading
Contract Name:
CalldataVerificationFacet
Compiler Version
v0.8.17+commit.8df45f5f
Optimization Enabled:
Yes with 1000000 runs
Other Settings:
london EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import { ILiFi } from "../Interfaces/ILiFi.sol"; import { LibSwap } from "../Libraries/LibSwap.sol"; import { AmarokFacet } from "./AmarokFacet.sol"; import { StargateFacet } from "./StargateFacet.sol"; import { CelerIMFacetBase, CelerIM } from "lifi/Helpers/CelerIMFacetBase.sol"; import { StandardizedCallFacet } from "lifi/Facets/StandardizedCallFacet.sol"; import { LibBytes } from "../Libraries/LibBytes.sol"; /// @title Calldata Verification Facet /// @author LI.FI (https://li.fi) /// @notice Provides functionality for verifying calldata /// @custom:version 1.1.1 contract CalldataVerificationFacet { using LibBytes for bytes; /// @notice Extracts the bridge data from the calldata /// @param data The calldata to extract the bridge data from /// @return bridgeData The bridge data extracted from the calldata function extractBridgeData( bytes calldata data ) external pure returns (ILiFi.BridgeData memory bridgeData) { bridgeData = _extractBridgeData(data); } /// @notice Extracts the swap data from the calldata /// @param data The calldata to extract the swap data from /// @return swapData The swap data extracted from the calldata function extractSwapData( bytes calldata data ) external pure returns (LibSwap.SwapData[] memory swapData) { swapData = _extractSwapData(data); } /// @notice Extracts the bridge data and swap data from the calldata /// @param data The calldata to extract the bridge data and swap data from /// @return bridgeData The bridge data extracted from the calldata /// @return swapData The swap data extracted from the calldata function extractData( bytes calldata data ) external pure returns ( ILiFi.BridgeData memory bridgeData, LibSwap.SwapData[] memory swapData ) { bridgeData = _extractBridgeData(data); if (bridgeData.hasSourceSwaps) { swapData = _extractSwapData(data); } } /// @notice Extracts the main parameters from the calldata /// @param data The calldata to extract the main parameters from /// @return bridge The bridge extracted from the calldata /// @return sendingAssetId The sending asset id extracted from the calldata /// @return receiver The receiver extracted from the calldata /// @return amount The min amountfrom the calldata /// @return destinationChainId The destination chain id extracted from the calldata /// @return hasSourceSwaps Whether the calldata has source swaps /// @return hasDestinationCall Whether the calldata has a destination call function extractMainParameters( bytes calldata data ) public pure returns ( string memory bridge, address sendingAssetId, address receiver, uint256 amount, uint256 destinationChainId, bool hasSourceSwaps, bool hasDestinationCall ) { ILiFi.BridgeData memory bridgeData = _extractBridgeData(data); if (bridgeData.hasSourceSwaps) { LibSwap.SwapData[] memory swapData = _extractSwapData(data); sendingAssetId = swapData[0].sendingAssetId; amount = swapData[0].fromAmount; } else { sendingAssetId = bridgeData.sendingAssetId; amount = bridgeData.minAmount; } return ( bridgeData.bridge, sendingAssetId, bridgeData.receiver, amount, bridgeData.destinationChainId, bridgeData.hasSourceSwaps, bridgeData.hasDestinationCall ); } /// @notice Extracts the generic swap parameters from the calldata /// @param data The calldata to extract the generic swap parameters from /// @return sendingAssetId The sending asset id extracted from the calldata /// @return amount The amount extracted from the calldata /// @return receiver The receiver extracted from the calldata /// @return receivingAssetId The receiving asset id extracted from the calldata /// @return receivingAmount The receiving amount extracted from the calldata function extractGenericSwapParameters( bytes calldata data ) public pure returns ( address sendingAssetId, uint256 amount, address receiver, address receivingAssetId, uint256 receivingAmount ) { LibSwap.SwapData[] memory swapData; bytes memory callData = data; if ( bytes4(data[:4]) == StandardizedCallFacet.standardizedCall.selector ) { // standardizedCall callData = abi.decode(data[4:], (bytes)); } (, , , receiver, receivingAmount, swapData) = abi.decode( callData.slice(4, callData.length - 4), (bytes32, string, string, address, uint256, LibSwap.SwapData[]) ); sendingAssetId = swapData[0].sendingAssetId; amount = swapData[0].fromAmount; receivingAssetId = swapData[swapData.length - 1].receivingAssetId; return ( sendingAssetId, amount, receiver, receivingAssetId, receivingAmount ); } /// @notice Validates the calldata /// @param data The calldata to validate /// @param bridge The bridge to validate or empty string to ignore /// @param sendingAssetId The sending asset id to validate /// or 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF to ignore /// @param receiver The receiver to validate /// or 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF to ignore /// @param amount The amount to validate or type(uint256).max to ignore /// @param destinationChainId The destination chain id to validate /// or type(uint256).max to ignore /// @param hasSourceSwaps Whether the calldata has source swaps /// @param hasDestinationCall Whether the calldata has a destination call /// @return isValid Whether the calldata is validate function validateCalldata( bytes calldata data, string calldata bridge, address sendingAssetId, address receiver, uint256 amount, uint256 destinationChainId, bool hasSourceSwaps, bool hasDestinationCall ) external pure returns (bool isValid) { ILiFi.BridgeData memory bridgeData; ( bridgeData.bridge, bridgeData.sendingAssetId, bridgeData.receiver, bridgeData.minAmount, bridgeData.destinationChainId, bridgeData.hasSourceSwaps, bridgeData.hasDestinationCall ) = extractMainParameters(data); return // Check bridge (keccak256(abi.encodePacked(bridge)) == keccak256(abi.encodePacked("")) || keccak256(abi.encodePacked(bridgeData.bridge)) == keccak256(abi.encodePacked(bridge))) && // Check sendingAssetId (sendingAssetId == 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF || bridgeData.sendingAssetId == sendingAssetId) && // Check receiver (receiver == 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF || bridgeData.receiver == receiver) && // Check amount (amount == type(uint256).max || bridgeData.minAmount == amount) && // Check destinationChainId (destinationChainId == type(uint256).max || bridgeData.destinationChainId == destinationChainId) && // Check hasSourceSwaps bridgeData.hasSourceSwaps == hasSourceSwaps && // Check hasDestinationCall bridgeData.hasDestinationCall == hasDestinationCall; } /// @notice Validates the destination calldata /// @param data The calldata to validate /// @param callTo The call to address to validate /// @param dstCalldata The destination calldata to validate /// @return isValid Whether the destination calldata is validate function validateDestinationCalldata( bytes calldata data, bytes calldata callTo, bytes calldata dstCalldata ) external pure returns (bool isValid) { bytes memory callData = data; // Handle standardizedCall if ( bytes4(data[:4]) == StandardizedCallFacet.standardizedCall.selector ) { callData = abi.decode(data[4:], (bytes)); } bytes4 selector = abi.decode(callData, (bytes4)); // Case: Amarok if (selector == AmarokFacet.startBridgeTokensViaAmarok.selector) { (, AmarokFacet.AmarokData memory amarokData) = abi.decode( callData.slice(4, callData.length - 4), (ILiFi.BridgeData, AmarokFacet.AmarokData) ); return keccak256(dstCalldata) == keccak256(amarokData.callData) && abi.decode(callTo, (address)) == amarokData.callTo; } if ( selector == AmarokFacet.swapAndStartBridgeTokensViaAmarok.selector ) { (, , AmarokFacet.AmarokData memory amarokData) = abi.decode( callData.slice(4, callData.length - 4), (ILiFi.BridgeData, LibSwap.SwapData[], AmarokFacet.AmarokData) ); return keccak256(dstCalldata) == keccak256(amarokData.callData) && abi.decode(callTo, (address)) == amarokData.callTo; } // Case: Stargate if (selector == StargateFacet.startBridgeTokensViaStargate.selector) { (, StargateFacet.StargateData memory stargateData) = abi.decode( callData.slice(4, callData.length - 4), (ILiFi.BridgeData, StargateFacet.StargateData) ); return keccak256(dstCalldata) == keccak256(stargateData.callData) && keccak256(callTo) == keccak256(stargateData.callTo); } if ( selector == StargateFacet.swapAndStartBridgeTokensViaStargate.selector ) { (, , StargateFacet.StargateData memory stargateData) = abi.decode( callData.slice(4, callData.length - 4), ( ILiFi.BridgeData, LibSwap.SwapData[], StargateFacet.StargateData ) ); return keccak256(dstCalldata) == keccak256(stargateData.callData) && keccak256(callTo) == keccak256(stargateData.callTo); } // Case: Celer if ( selector == CelerIMFacetBase.startBridgeTokensViaCelerIM.selector ) { (, CelerIM.CelerIMData memory celerIMData) = abi.decode( callData.slice(4, callData.length - 4), (ILiFi.BridgeData, CelerIM.CelerIMData) ); return keccak256(dstCalldata) == keccak256(celerIMData.callData) && keccak256(callTo) == keccak256(celerIMData.callTo); } if ( selector == CelerIMFacetBase.swapAndStartBridgeTokensViaCelerIM.selector ) { (, , CelerIM.CelerIMData memory celerIMData) = abi.decode( callData.slice(4, callData.length - 4), (ILiFi.BridgeData, LibSwap.SwapData[], CelerIM.CelerIMData) ); return keccak256(dstCalldata) == keccak256(celerIMData.callData) && keccak256(callTo) == keccak256(celerIMData.callTo); } // All other cases return false; } /// Internal Methods /// /// @notice Extracts the bridge data from the calldata /// @param data The calldata to extract the bridge data from /// @return bridgeData The bridge data extracted from the calldata function _extractBridgeData( bytes calldata data ) internal pure returns (ILiFi.BridgeData memory bridgeData) { if ( bytes4(data[:4]) == StandardizedCallFacet.standardizedCall.selector ) { // StandardizedCall bytes memory unwrappedData = abi.decode(data[4:], (bytes)); bridgeData = abi.decode( unwrappedData.slice(4, unwrappedData.length - 4), (ILiFi.BridgeData) ); return bridgeData; } // normal call bridgeData = abi.decode(data[4:], (ILiFi.BridgeData)); } /// @notice Extracts the swap data from the calldata /// @param data The calldata to extract the swap data from /// @return swapData The swap data extracted from the calldata function _extractSwapData( bytes calldata data ) internal pure returns (LibSwap.SwapData[] memory swapData) { if ( bytes4(data[:4]) == StandardizedCallFacet.standardizedCall.selector ) { // standardizedCall bytes memory unwrappedData = abi.decode(data[4:], (bytes)); (, swapData) = abi.decode( unwrappedData.slice(4, unwrappedData.length - 4), (ILiFi.BridgeData, LibSwap.SwapData[]) ); return swapData; } // normal call (, swapData) = abi.decode( data[4:], (ILiFi.BridgeData, LibSwap.SwapData[]) ); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; interface ILiFi { /// Structs /// struct BridgeData { bytes32 transactionId; string bridge; string integrator; address referrer; address sendingAssetId; address receiver; uint256 minAmount; uint256 destinationChainId; bool hasSourceSwaps; bool hasDestinationCall; } /// Events /// event LiFiTransferStarted(ILiFi.BridgeData bridgeData); event LiFiTransferCompleted( bytes32 indexed transactionId, address receivingAssetId, address receiver, uint256 amount, uint256 timestamp ); event LiFiTransferRecovered( bytes32 indexed transactionId, address receivingAssetId, address receiver, uint256 amount, uint256 timestamp ); event LiFiGenericSwapCompleted( bytes32 indexed transactionId, string integrator, string referrer, address receiver, address fromAssetId, address toAssetId, uint256 fromAmount, uint256 toAmount ); // Deprecated but kept here to include in ABI to parse historic events event LiFiSwappedGeneric( bytes32 indexed transactionId, string integrator, string referrer, address fromAssetId, address toAssetId, uint256 fromAmount, uint256 toAmount ); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import { LibAsset } from "./LibAsset.sol"; import { LibUtil } from "./LibUtil.sol"; import { InvalidContract, NoSwapFromZeroBalance, InsufficientBalance } from "../Errors/GenericErrors.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library LibSwap { struct SwapData { address callTo; address approveTo; address sendingAssetId; address receivingAssetId; uint256 fromAmount; bytes callData; bool requiresDeposit; } event AssetSwapped( bytes32 transactionId, address dex, address fromAssetId, address toAssetId, uint256 fromAmount, uint256 toAmount, uint256 timestamp ); function swap(bytes32 transactionId, SwapData calldata _swap) internal { if (!LibAsset.isContract(_swap.callTo)) revert InvalidContract(); uint256 fromAmount = _swap.fromAmount; if (fromAmount == 0) revert NoSwapFromZeroBalance(); uint256 nativeValue = LibAsset.isNativeAsset(_swap.sendingAssetId) ? _swap.fromAmount : 0; uint256 initialSendingAssetBalance = LibAsset.getOwnBalance( _swap.sendingAssetId ); uint256 initialReceivingAssetBalance = LibAsset.getOwnBalance( _swap.receivingAssetId ); if (nativeValue == 0) { LibAsset.maxApproveERC20( IERC20(_swap.sendingAssetId), _swap.approveTo, _swap.fromAmount ); } if (initialSendingAssetBalance < _swap.fromAmount) { revert InsufficientBalance( _swap.fromAmount, initialSendingAssetBalance ); } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory res) = _swap.callTo.call{ value: nativeValue }(_swap.callData); if (!success) { string memory reason = LibUtil.getRevertMsg(res); revert(reason); } uint256 newBalance = LibAsset.getOwnBalance(_swap.receivingAssetId); emit AssetSwapped( transactionId, _swap.callTo, _swap.sendingAssetId, _swap.receivingAssetId, _swap.fromAmount, newBalance > initialReceivingAssetBalance ? newBalance - initialReceivingAssetBalance : newBalance, block.timestamp ); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import { ILiFi } from "../Interfaces/ILiFi.sol"; import { IConnextHandler } from "../Interfaces/IConnextHandler.sol"; import { LibAsset, IERC20 } from "../Libraries/LibAsset.sol"; import { ReentrancyGuard } from "../Helpers/ReentrancyGuard.sol"; import { InformationMismatch } from "../Errors/GenericErrors.sol"; import { SwapperV2, LibSwap } from "../Helpers/SwapperV2.sol"; import { Validatable } from "../Helpers/Validatable.sol"; /// @title Amarok Facet /// @author LI.FI (https://li.fi) /// @notice Provides functionality for bridging through Connext Amarok /// @custom:version 2.0.0 contract AmarokFacet is ILiFi, ReentrancyGuard, SwapperV2, Validatable { /// Storage /// /// @notice The contract address of the connext handler on the source chain. IConnextHandler private immutable connextHandler; /// @param callData The data to execute on the receiving chain. If no crosschain call is needed, then leave empty. /// @param callTo The address of the contract on dest chain that will receive bridged funds and execute data /// @param relayerFee The amount of relayer fee the tx called xcall with /// @param slippageTol Max bps of original due to slippage (i.e. would be 9995 to tolerate .05% slippage) /// @param delegate Destination delegate address /// @param destChainDomainId The Amarok-specific domainId of the destination chain /// @param payFeeWithSendingAsset Whether to pay the relayer fee with the sending asset or not struct AmarokData { bytes callData; address callTo; uint256 relayerFee; uint256 slippageTol; address delegate; uint32 destChainDomainId; bool payFeeWithSendingAsset; } /// Constructor /// /// @notice Initialize the contract. /// @param _connextHandler The contract address of the connext handler on the source chain. constructor(IConnextHandler _connextHandler) { connextHandler = _connextHandler; } /// External Methods /// /// @notice Bridges tokens via Amarok /// @param _bridgeData Data containing core information for bridging /// @param _amarokData Data specific to bridge function startBridgeTokensViaAmarok( BridgeData calldata _bridgeData, AmarokData calldata _amarokData ) external payable nonReentrant refundExcessNative(payable(msg.sender)) doesNotContainSourceSwaps(_bridgeData) validateBridgeData(_bridgeData) noNativeAsset(_bridgeData) { validateDestinationCallFlag(_bridgeData, _amarokData); LibAsset.depositAsset( _bridgeData.sendingAssetId, _bridgeData.minAmount ); _startBridge(_bridgeData, _amarokData); } /// @notice Performs a swap before bridging via Amarok /// @param _bridgeData The core information needed for bridging /// @param _swapData An array of swap related data for performing swaps before bridging /// @param _amarokData Data specific to Amarok function swapAndStartBridgeTokensViaAmarok( BridgeData memory _bridgeData, LibSwap.SwapData[] calldata _swapData, AmarokData calldata _amarokData ) external payable nonReentrant refundExcessNative(payable(msg.sender)) containsSourceSwaps(_bridgeData) validateBridgeData(_bridgeData) noNativeAsset(_bridgeData) { validateDestinationCallFlag(_bridgeData, _amarokData); _bridgeData.minAmount = _depositAndSwap( _bridgeData.transactionId, _bridgeData.minAmount, _swapData, payable(msg.sender), _amarokData.relayerFee ); _startBridge(_bridgeData, _amarokData); } /// Private Methods /// /// @dev Contains the business logic for the bridge via Amarok /// @param _bridgeData The core information needed for bridging /// @param _amarokData Data specific to Amarok function _startBridge( BridgeData memory _bridgeData, AmarokData calldata _amarokData ) private { // give max approval for token to Amarok bridge, if not already LibAsset.maxApproveERC20( IERC20(_bridgeData.sendingAssetId), address(connextHandler), _bridgeData.minAmount ); // initiate bridge transaction if (_amarokData.payFeeWithSendingAsset) { connextHandler.xcall( _amarokData.destChainDomainId, _amarokData.callTo, _bridgeData.sendingAssetId, _amarokData.delegate, _bridgeData.minAmount - _amarokData.relayerFee, _amarokData.slippageTol, _amarokData.callData, _amarokData.relayerFee ); } else { connextHandler.xcall{ value: _amarokData.relayerFee }( _amarokData.destChainDomainId, _amarokData.callTo, _bridgeData.sendingAssetId, _amarokData.delegate, _bridgeData.minAmount, _amarokData.slippageTol, _amarokData.callData ); } emit LiFiTransferStarted(_bridgeData); } function validateDestinationCallFlag( ILiFi.BridgeData memory _bridgeData, AmarokData calldata _amarokData ) private pure { if ( (_amarokData.callData.length > 0) != _bridgeData.hasDestinationCall ) { revert InformationMismatch(); } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import { ILiFi } from "../Interfaces/ILiFi.sol"; import { IStargateRouter } from "../Interfaces/IStargateRouter.sol"; import { LibAsset, IERC20 } from "../Libraries/LibAsset.sol"; import { LibDiamond } from "../Libraries/LibDiamond.sol"; import { ReentrancyGuard } from "../Helpers/ReentrancyGuard.sol"; import { InformationMismatch, AlreadyInitialized, NotInitialized } from "../Errors/GenericErrors.sol"; import { SwapperV2, LibSwap } from "../Helpers/SwapperV2.sol"; import { Validatable } from "../Helpers/Validatable.sol"; /// @title Stargate Facet /// @author Li.Finance (https://li.finance) /// @notice Provides functionality for bridging through Stargate /// @custom:version 2.1.0 contract StargateFacet is ILiFi, ReentrancyGuard, SwapperV2, Validatable { /// CONSTANTS /// /// @notice The contract address of the stargate router on the source chain. IStargateRouter private immutable router; /// @notice The contract address of the native stargate router on the source chain. IStargateRouter private immutable nativeRouter; /// @notice The contract address of the stargate composer on the source chain. IStargateRouter private immutable composer; /// Storage /// bytes32 internal constant NAMESPACE = keccak256("com.lifi.facets.stargate"); /// Types /// struct Storage { mapping(uint256 => uint16) layerZeroChainId; bool initialized; } struct ChainIdConfig { uint256 chainId; uint16 layerZeroChainId; } /// @param srcPoolId Source pool id. /// @param dstPoolId Dest pool id. /// @param minAmountLD The min qty you would accept on the destination. /// @param dstGasForCall Additional gas fee for extral call on the destination. /// @param lzFee Estimated message fee. /// @param refundAddress Refund adddress. Extra gas (if any) is returned to this address /// @param callTo The address to send the tokens to on the destination. /// @param callData Additional payload. struct StargateData { uint256 srcPoolId; uint256 dstPoolId; uint256 minAmountLD; uint256 dstGasForCall; uint256 lzFee; address payable refundAddress; bytes callTo; bytes callData; } /// Errors /// error UnknownLayerZeroChain(); /// Events /// event StargateInitialized(ChainIdConfig[] chainIdConfigs); event LayerZeroChainIdSet( uint256 indexed chainId, uint16 layerZeroChainId ); /// @notice Emit to get credited for referral /// @dev Our partner id is 0x0006 event PartnerSwap(bytes2 partnerId); /// Constructor /// /// @notice Initialize the contract. /// @param _router The contract address of the stargate router on the source chain. /// @param _nativeRouter The contract address of the native token stargate router on the source chain. constructor( IStargateRouter _router, IStargateRouter _nativeRouter, IStargateRouter _composer ) { router = _router; nativeRouter = _nativeRouter; composer = _composer; } /// Init /// /// @notice Initialize local variables for the Stargate Facet /// @param chainIdConfigs Chain Id configuration data function initStargate(ChainIdConfig[] calldata chainIdConfigs) external { LibDiamond.enforceIsContractOwner(); Storage storage sm = getStorage(); for (uint256 i = 0; i < chainIdConfigs.length; i++) { sm.layerZeroChainId[chainIdConfigs[i].chainId] = chainIdConfigs[i] .layerZeroChainId; } sm.initialized = true; emit StargateInitialized(chainIdConfigs); } /// External Methods /// /// @notice Bridges tokens via Stargate Bridge /// @param _bridgeData Data used purely for tracking and analytics /// @param _stargateData Data specific to Stargate Bridge function startBridgeTokensViaStargate( ILiFi.BridgeData calldata _bridgeData, StargateData calldata _stargateData ) external payable nonReentrant refundExcessNative(payable(msg.sender)) doesNotContainSourceSwaps(_bridgeData) validateBridgeData(_bridgeData) { validateDestinationCallFlag(_bridgeData, _stargateData); LibAsset.depositAsset( _bridgeData.sendingAssetId, _bridgeData.minAmount ); _startBridge(_bridgeData, _stargateData); } /// @notice Performs a swap before bridging via Stargate Bridge /// @param _bridgeData Data used purely for tracking and analytics /// @param _swapData An array of swap related data for performing swaps before bridging /// @param _stargateData Data specific to Stargate Bridge function swapAndStartBridgeTokensViaStargate( ILiFi.BridgeData memory _bridgeData, LibSwap.SwapData[] calldata _swapData, StargateData calldata _stargateData ) external payable nonReentrant refundExcessNative(payable(msg.sender)) containsSourceSwaps(_bridgeData) validateBridgeData(_bridgeData) { validateDestinationCallFlag(_bridgeData, _stargateData); _bridgeData.minAmount = _depositAndSwap( _bridgeData.transactionId, _bridgeData.minAmount, _swapData, payable(msg.sender), LibAsset.isNativeAsset(_bridgeData.sendingAssetId) ? 0 : _stargateData.lzFee ); _startBridge(_bridgeData, _stargateData); } function quoteLayerZeroFee( uint256 _destinationChainId, StargateData calldata _stargateData ) external view returns (uint256, uint256) { // Transfers with callData have to be routed via the composer which adds additional overhead in fees. // The composer exposes the same function as the router to calculate those fees. IStargateRouter stargate = _stargateData.callData.length > 0 ? composer : router; return stargate.quoteLayerZeroFee( getLayerZeroChainId(_destinationChainId), 1, // TYPE_SWAP_REMOTE on Bridge _stargateData.callTo, _stargateData.callData, IStargateRouter.lzTxObj( _stargateData.dstGasForCall, 0, toBytes(address(0)) ) ); } /// Private Methods /// /// @dev Contains the business logic for the bridge via Stargate Bridge /// @param _bridgeData Data used purely for tracking and analytics /// @param _stargateData Data specific to Stargate Bridge function _startBridge( ILiFi.BridgeData memory _bridgeData, StargateData calldata _stargateData ) private { if (LibAsset.isNativeAsset(_bridgeData.sendingAssetId)) { // All transfers with destination calls need to be routed via the composer contract IStargateRouter stargate = _bridgeData.hasDestinationCall ? composer : nativeRouter; stargate.swapETHAndCall{ value: _bridgeData.minAmount }( getLayerZeroChainId(_bridgeData.destinationChainId), _stargateData.refundAddress, _stargateData.callTo, IStargateRouter.SwapAmount( _bridgeData.minAmount - _stargateData.lzFee, _stargateData.minAmountLD ), IStargateRouter.lzTxObj( _stargateData.dstGasForCall, 0, toBytes(address(0)) ), _stargateData.callData ); } else { // All transfers with destination calls need to be routed via the composer contract IStargateRouter stargate = _bridgeData.hasDestinationCall ? composer : router; LibAsset.maxApproveERC20( IERC20(_bridgeData.sendingAssetId), address(stargate), _bridgeData.minAmount ); stargate.swap{ value: _stargateData.lzFee }( getLayerZeroChainId(_bridgeData.destinationChainId), _stargateData.srcPoolId, _stargateData.dstPoolId, _stargateData.refundAddress, _bridgeData.minAmount, _stargateData.minAmountLD, IStargateRouter.lzTxObj( _stargateData.dstGasForCall, 0, toBytes(address(0)) ), _stargateData.callTo, _stargateData.callData ); } emit PartnerSwap(0x0006); emit LiFiTransferStarted(_bridgeData); } function validateDestinationCallFlag( ILiFi.BridgeData memory _bridgeData, StargateData calldata _stargateData ) private pure { if ( (_stargateData.callData.length > 0) != _bridgeData.hasDestinationCall ) { revert InformationMismatch(); } } /// Mappings management /// /// @notice Sets the Layer 0 chain ID for a given chain ID /// @param _chainId uint16 of the chain ID /// @param _layerZeroChainId uint16 of the Layer 0 chain ID /// @dev This is used to map a chain ID to its Layer 0 chain ID function setLayerZeroChainId( uint256 _chainId, uint16 _layerZeroChainId ) external { LibDiamond.enforceIsContractOwner(); Storage storage sm = getStorage(); if (!sm.initialized) { revert NotInitialized(); } sm.layerZeroChainId[_chainId] = _layerZeroChainId; emit LayerZeroChainIdSet(_chainId, _layerZeroChainId); } /// @notice Gets the Layer 0 chain ID for a given chain ID /// @param _chainId uint256 of the chain ID /// @return uint16 of the Layer 0 chain ID function getLayerZeroChainId( uint256 _chainId ) private view returns (uint16) { Storage storage sm = getStorage(); uint16 chainId = sm.layerZeroChainId[_chainId]; if (chainId == 0) revert UnknownLayerZeroChain(); return chainId; } function toBytes(address _address) private pure returns (bytes memory) { return abi.encodePacked(_address); } /// @dev fetch local storage function getStorage() private pure returns (Storage storage s) { bytes32 namespace = NAMESPACE; // solhint-disable-next-line no-inline-assembly assembly { s.slot := namespace } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { LibAsset, IERC20 } from "../Libraries/LibAsset.sol"; import { ERC20 } from "solmate/tokens/ERC20.sol"; import { ILiFi } from "../Interfaces/ILiFi.sol"; import { ReentrancyGuard } from "../Helpers/ReentrancyGuard.sol"; import { SwapperV2, LibSwap } from "../Helpers/SwapperV2.sol"; import { InvalidAmount, InformationMismatch } from "../Errors/GenericErrors.sol"; import { Validatable } from "../Helpers/Validatable.sol"; import { MessageSenderLib, MsgDataTypes, IMessageBus } from "celer-network/contracts/message/libraries/MessageSenderLib.sol"; import { RelayerCelerIM } from "lifi/Periphery/RelayerCelerIM.sol"; interface CelerToken { function canonical() external returns (address); } interface CelerIM { /// @param maxSlippage The max slippage accepted, given as percentage in point (pip). /// @param nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice. /// @param callTo The address of the contract to be called at destination. /// @param callData The encoded calldata with below data /// bytes32 transactionId, /// LibSwap.SwapData[] memory swapData, /// address receiver, /// address refundAddress /// @param messageBusFee The fee to be paid to CBridge message bus for relaying the message /// @param bridgeType Defines the bridge operation type (must be one of the values of CBridge library MsgDataTypes.BridgeSendType) struct CelerIMData { uint32 maxSlippage; uint64 nonce; bytes callTo; bytes callData; uint256 messageBusFee; MsgDataTypes.BridgeSendType bridgeType; } } /// @title CelerIM Facet Base /// @author LI.FI (https://li.fi) /// @notice Provides functionality for bridging tokens and data through CBridge /// @notice Used to differentiate between contract instances for mutable and immutable diamond as these cannot be shared /// @custom:version 2.0.0 abstract contract CelerIMFacetBase is ILiFi, ReentrancyGuard, SwapperV2, Validatable { /// Storage /// /// @dev The contract address of the cBridge Message Bus IMessageBus private immutable cBridgeMessageBus; /// @dev The contract address of the RelayerCelerIM RelayerCelerIM public immutable relayer; /// @dev The contract address of the Celer Flow USDC address private immutable cfUSDC; /// Constructor /// /// @notice Initialize the contract. /// @param _messageBus The contract address of the cBridge Message Bus /// @param _relayerOwner The address that will become the owner of the RelayerCelerIM contract /// @param _diamondAddress The address of the diamond contract that will be connected with the RelayerCelerIM /// @param _cfUSDC The contract address of the Celer Flow USDC constructor( IMessageBus _messageBus, address _relayerOwner, address _diamondAddress, address _cfUSDC ) { // deploy RelayerCelerIM relayer = new RelayerCelerIM( address(_messageBus), _relayerOwner, _diamondAddress ); // store arguments in variables cBridgeMessageBus = _messageBus; cfUSDC = _cfUSDC; } /// External Methods /// /// @notice Bridges tokens via CBridge /// @param _bridgeData The core information needed for bridging /// @param _celerIMData Data specific to CelerIM function startBridgeTokensViaCelerIM( ILiFi.BridgeData memory _bridgeData, CelerIM.CelerIMData calldata _celerIMData ) external payable nonReentrant refundExcessNative(payable(msg.sender)) doesNotContainSourceSwaps(_bridgeData) validateBridgeData(_bridgeData) { validateDestinationCallFlag(_bridgeData, _celerIMData); if (!LibAsset.isNativeAsset(_bridgeData.sendingAssetId)) { // Transfer ERC20 tokens directly to relayer IERC20 asset = _getRightAsset(_bridgeData.sendingAssetId); // Deposit ERC20 token uint256 prevBalance = asset.balanceOf(address(relayer)); SafeERC20.safeTransferFrom( asset, msg.sender, address(relayer), _bridgeData.minAmount ); if ( asset.balanceOf(address(relayer)) - prevBalance != _bridgeData.minAmount ) { revert InvalidAmount(); } } _startBridge(_bridgeData, _celerIMData); } /// @notice Performs a swap before bridging via CBridge /// @param _bridgeData The core information needed for bridging /// @param _swapData An array of swap related data for performing swaps before bridging /// @param _celerIMData Data specific to CelerIM function swapAndStartBridgeTokensViaCelerIM( ILiFi.BridgeData memory _bridgeData, LibSwap.SwapData[] calldata _swapData, CelerIM.CelerIMData calldata _celerIMData ) external payable nonReentrant refundExcessNative(payable(msg.sender)) containsSourceSwaps(_bridgeData) validateBridgeData(_bridgeData) { validateDestinationCallFlag(_bridgeData, _celerIMData); _bridgeData.minAmount = _depositAndSwap( _bridgeData.transactionId, _bridgeData.minAmount, _swapData, payable(msg.sender), _celerIMData.messageBusFee ); if (!LibAsset.isNativeAsset(_bridgeData.sendingAssetId)) { // Transfer ERC20 tokens directly to relayer IERC20 asset = _getRightAsset(_bridgeData.sendingAssetId); // Deposit ERC20 token uint256 prevBalance = asset.balanceOf(address(relayer)); SafeERC20.safeTransfer( asset, address(relayer), _bridgeData.minAmount ); if ( asset.balanceOf(address(relayer)) - prevBalance != _bridgeData.minAmount ) { revert InvalidAmount(); } } _startBridge(_bridgeData, _celerIMData); } /// Private Methods /// /// @dev Contains the business logic for the bridge via CBridge /// @param _bridgeData The core information needed for bridging /// @param _celerIMData Data specific to CBridge function _startBridge( ILiFi.BridgeData memory _bridgeData, CelerIM.CelerIMData calldata _celerIMData ) private { // Assuming messageBusFee is pre-calculated off-chain and available in _celerIMData // Determine correct native asset amount to be forwarded (if so) and send funds to relayer uint256 msgValue = LibAsset.isNativeAsset(_bridgeData.sendingAssetId) ? _bridgeData.minAmount : 0; // Check if transaction contains a destination call if (!_bridgeData.hasDestinationCall) { // Case 'no': Simple bridge transfer - Send to receiver relayer.sendTokenTransfer{ value: msgValue }( _bridgeData, _celerIMData ); } else { // Case 'yes': Bridge + Destination call - Send to relayer // save address of original recipient address receiver = _bridgeData.receiver; // Set relayer as a receiver _bridgeData.receiver = address(relayer); // send token transfer (bytes32 transferId, address bridgeAddress) = relayer .sendTokenTransfer{ value: msgValue }( _bridgeData, _celerIMData ); // Call message bus via relayer incl messageBusFee relayer.forwardSendMessageWithTransfer{ value: _celerIMData.messageBusFee }( _bridgeData.receiver, uint64(_bridgeData.destinationChainId), bridgeAddress, transferId, _celerIMData.callData ); // Reset receiver of bridge data for event emission _bridgeData.receiver = receiver; } // emit LiFi event emit LiFiTransferStarted(_bridgeData); } /// @dev Get right asset to transfer to relayer. /// @param _sendingAssetId The address of asset to bridge. /// @return _asset The address of asset to transfer to relayer. function _getRightAsset( address _sendingAssetId ) private returns (IERC20 _asset) { if (_sendingAssetId == cfUSDC) { // special case for cfUSDC token _asset = IERC20(CelerToken(_sendingAssetId).canonical()); } else { // any other ERC20 token _asset = IERC20(_sendingAssetId); } } function validateDestinationCallFlag( ILiFi.BridgeData memory _bridgeData, CelerIM.CelerIMData calldata _celerIMData ) private pure { if ( (_celerIMData.callData.length > 0) != _bridgeData.hasDestinationCall ) { revert InformationMismatch(); } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import { LibDiamond } from "../Libraries/LibDiamond.sol"; /// @title Standardized Call Facet /// @author LIFI https://li.finance [email protected] /// @notice Allows calling different facet methods through a single standardized entrypoint /// @custom:version 1.0.0 contract StandardizedCallFacet { /// External Methods /// /// @notice Make a standardized call to a facet /// @param callData The calldata to forward to the facet function standardizedCall(bytes memory callData) external payable { // Fetch the facetAddress from the dimaond's internal storage // Cheaper than calling the external facetAddress(selector) method directly LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); address facetAddress = ds .selectorToFacetAndPosition[bytes4(callData)] .facetAddress; if (facetAddress == address(0)) { revert LibDiamond.FunctionDoesNotExist(); } // Execute external function from facet using delegatecall and return any value. // solhint-disable-next-line no-inline-assembly assembly { // execute function call using the facet let result := delegatecall( gas(), facetAddress, add(callData, 0x20), mload(callData), 0, 0 ) // get any return value returndatacopy(0, 0, returndatasize()) // return any return value or error back to the caller switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; library LibBytes { // solhint-disable no-inline-assembly // LibBytes specific errors error SliceOverflow(); error SliceOutOfBounds(); error AddressOutOfBounds(); bytes16 private constant _SYMBOLS = "0123456789abcdef"; // ------------------------- function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { if (_length + 31 < _length) revert SliceOverflow(); if (_bytes.length < _start + _length) revert SliceOutOfBounds(); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add( add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)) ) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add( add( add(_bytes, lengthmod), mul(0x20, iszero(lengthmod)) ), _start ) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress( bytes memory _bytes, uint256 _start ) internal pure returns (address) { if (_bytes.length < _start + 20) { revert AddressOutOfBounds(); } address tempAddress; assembly { tempAddress := div( mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000 ) } return tempAddress; } /// Copied from OpenZeppelin's `Strings.sol` utility library. /// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/8335676b0e99944eef6a742e16dcd9ff6e68e609/contracts/utils/Strings.sol function toHexString( uint256 value, uint256 length ) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.17; import { InsufficientBalance, NullAddrIsNotAnERC20Token, NullAddrIsNotAValidSpender, NoTransferToNullAddress, InvalidAmount, NativeAssetTransferFailed } from "../Errors/GenericErrors.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { LibSwap } from "./LibSwap.sol"; /// @title LibAsset /// @notice This library contains helpers for dealing with onchain transfers /// of assets, including accounting for the native asset `assetId` /// conventions and any noncompliant ERC20 transfers library LibAsset { uint256 private constant MAX_UINT = type(uint256).max; address internal constant NULL_ADDRESS = address(0); /// @dev All native assets use the empty address for their asset id /// by convention address internal constant NATIVE_ASSETID = NULL_ADDRESS; //address(0) /// @notice Gets the balance of the inheriting contract for the given asset /// @param assetId The asset identifier to get the balance of /// @return Balance held by contracts using this library function getOwnBalance(address assetId) internal view returns (uint256) { return isNativeAsset(assetId) ? address(this).balance : IERC20(assetId).balanceOf(address(this)); } /// @notice Transfers ether from the inheriting contract to a given /// recipient /// @param recipient Address to send ether to /// @param amount Amount to send to given recipient function transferNativeAsset( address payable recipient, uint256 amount ) private { if (recipient == NULL_ADDRESS) revert NoTransferToNullAddress(); if (amount > address(this).balance) revert InsufficientBalance(amount, address(this).balance); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = recipient.call{ value: amount }(""); if (!success) revert NativeAssetTransferFailed(); } /// @notice If the current allowance is insufficient, the allowance for a given spender /// is set to MAX_UINT. /// @param assetId Token address to transfer /// @param spender Address to give spend approval to /// @param amount Amount to approve for spending function maxApproveERC20( IERC20 assetId, address spender, uint256 amount ) internal { if (isNativeAsset(address(assetId))) { return; } if (spender == NULL_ADDRESS) { revert NullAddrIsNotAValidSpender(); } if (assetId.allowance(address(this), spender) < amount) { SafeERC20.safeApprove(IERC20(assetId), spender, 0); SafeERC20.safeApprove(IERC20(assetId), spender, MAX_UINT); } } /// @notice Transfers tokens from the inheriting contract to a given /// recipient /// @param assetId Token address to transfer /// @param recipient Address to send token to /// @param amount Amount to send to given recipient function transferERC20( address assetId, address recipient, uint256 amount ) private { if (isNativeAsset(assetId)) { revert NullAddrIsNotAnERC20Token(); } if (recipient == NULL_ADDRESS) { revert NoTransferToNullAddress(); } uint256 assetBalance = IERC20(assetId).balanceOf(address(this)); if (amount > assetBalance) { revert InsufficientBalance(amount, assetBalance); } SafeERC20.safeTransfer(IERC20(assetId), recipient, amount); } /// @notice Transfers tokens from a sender to a given recipient /// @param assetId Token address to transfer /// @param from Address of sender/owner /// @param to Address of recipient/spender /// @param amount Amount to transfer from owner to spender function transferFromERC20( address assetId, address from, address to, uint256 amount ) internal { if (isNativeAsset(assetId)) { revert NullAddrIsNotAnERC20Token(); } if (to == NULL_ADDRESS) { revert NoTransferToNullAddress(); } IERC20 asset = IERC20(assetId); uint256 prevBalance = asset.balanceOf(to); SafeERC20.safeTransferFrom(asset, from, to, amount); if (asset.balanceOf(to) - prevBalance != amount) { revert InvalidAmount(); } } function depositAsset(address assetId, uint256 amount) internal { if (amount == 0) revert InvalidAmount(); if (isNativeAsset(assetId)) { if (msg.value < amount) revert InvalidAmount(); } else { uint256 balance = IERC20(assetId).balanceOf(msg.sender); if (balance < amount) revert InsufficientBalance(amount, balance); transferFromERC20(assetId, msg.sender, address(this), amount); } } function depositAssets(LibSwap.SwapData[] calldata swaps) internal { for (uint256 i = 0; i < swaps.length; ) { LibSwap.SwapData calldata swap = swaps[i]; if (swap.requiresDeposit) { depositAsset(swap.sendingAssetId, swap.fromAmount); } unchecked { i++; } } } /// @notice Determines whether the given assetId is the native asset /// @param assetId The asset identifier to evaluate /// @return Boolean indicating if the asset is the native asset function isNativeAsset(address assetId) internal pure returns (bool) { return assetId == NATIVE_ASSETID; } /// @notice Wrapper function to transfer a given asset (native or erc20) to /// some recipient. Should handle all non-compliant return value /// tokens as well by using the SafeERC20 contract by open zeppelin. /// @param assetId Asset id for transfer (address(0) for native asset, /// token address for erc20s) /// @param recipient Address to send asset to /// @param amount Amount to send to given recipient function transferAsset( address assetId, address payable recipient, uint256 amount ) internal { isNativeAsset(assetId) ? transferNativeAsset(recipient, amount) : transferERC20(assetId, recipient, amount); } /// @dev Checks whether the given address is a contract and contains code function isContract(address _contractAddr) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(_contractAddr) } return size > 0; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import "./LibBytes.sol"; library LibUtil { using LibBytes for bytes; function getRevertMsg( bytes memory _res ) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_res.length < 68) return "Transaction reverted silently"; bytes memory revertData = _res.slice(4, _res.length - 4); // Remove the selector which is the first 4 bytes return abi.decode(revertData, (string)); // All that remains is the revert string } /// @notice Determines whether the given address is the zero address /// @param addr The address to verify /// @return Boolean indicating if the address is the zero address function isZeroAddress(address addr) internal pure returns (bool) { return addr == address(0); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; error AlreadyInitialized(); error CannotAuthoriseSelf(); error CannotBridgeToSameNetwork(); error ContractCallNotAllowed(); error CumulativeSlippageTooHigh(uint256 minAmount, uint256 receivedAmount); error ExternalCallFailed(); error InformationMismatch(); error InsufficientBalance(uint256 required, uint256 balance); error InvalidAmount(); error InvalidCallData(); error InvalidConfig(); error InvalidContract(); error InvalidDestinationChain(); error InvalidFallbackAddress(); error InvalidReceiver(); error InvalidSendingToken(); error NativeAssetNotSupported(); error NativeAssetTransferFailed(); error NoSwapDataProvided(); error NoSwapFromZeroBalance(); error NotAContract(); error NotInitialized(); error NoTransferToNullAddress(); error NullAddrIsNotAnERC20Token(); error NullAddrIsNotAValidSpender(); error OnlyContractOwner(); error RecoveryAddressCannotBeZero(); error ReentrancyError(); error TokenNotSupported(); error UnAuthorized(); error UnsupportedChainId(uint256 chainId); error WithdrawFailed(); error ZeroAmount();
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 amount) external returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; interface IConnextHandler { /// @notice These are the call parameters that will remain constant between the /// two chains. They are supplied on `xcall` and should be asserted on `execute` /// @property to - The account that receives funds, in the event of a crosschain call, /// will receive funds if the call fails. /// @param to - The address you are sending funds (and potentially data) to /// @param callData - The data to execute on the receiving chain. If no crosschain call is needed, then leave empty. /// @param originDomain - The originating domain (i.e. where `xcall` is called). Must match nomad domain schema /// @param destinationDomain - The final domain (i.e. where `execute` / `reconcile` are called). Must match nomad domain schema /// @param agent - An address who can execute txs on behalf of `to`, in addition to allowing relayers /// @param recovery - The address to send funds to if your `Executor.execute call` fails /// @param forceSlow - If true, will take slow liquidity path even if it is not a permissioned call /// @param receiveLocal - If true, will use the local nomad asset on the destination instead of adopted. /// @param callback - The address on the origin domain of the callback contract /// @param callbackFee - The relayer fee to execute the callback /// @param relayerFee - The amount of relayer fee the tx called xcall with /// @param slippageTol - Max bps of original due to slippage (i.e. would be 9995 to tolerate .05% slippage) struct CallParams { address to; bytes callData; uint32 originDomain; uint32 destinationDomain; address agent; address recovery; bool forceSlow; bool receiveLocal; address callback; uint256 callbackFee; uint256 relayerFee; uint256 slippageTol; } /// @notice The arguments you supply to the `xcall` function called by user on origin domain /// @param params - The CallParams. These are consistent across sending and receiving chains /// @param transactingAsset - The asset the caller sent with the transfer. Can be the adopted, canonical, /// or the representational asset /// @param transactingAmount - The amount of transferring asset supplied by the user in the `xcall` /// @param originMinOut - Minimum amount received on swaps for adopted <> local on origin chain struct XCallArgs { CallParams params; address transactingAsset; // Could be adopted, local, or wrapped uint256 transactingAmount; uint256 originMinOut; } function xcall( uint32 destination, address recipient, address tokenAddress, address delegate, uint256 amount, uint256 slippage, bytes memory callData ) external payable returns (bytes32); function xcall( uint32 destination, address recipient, address tokenAddress, address delegate, uint256 amount, uint256 slippage, bytes memory callData, uint256 _relayerFee ) external returns (bytes32); }
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.17; /// @title Reentrancy Guard /// @author LI.FI (https://li.fi) /// @notice Abstract contract to provide protection against reentrancy abstract contract ReentrancyGuard { /// Storage /// bytes32 private constant NAMESPACE = keccak256("com.lifi.reentrancyguard"); /// Types /// struct ReentrancyStorage { uint256 status; } /// Errors /// error ReentrancyError(); /// Constants /// uint256 private constant _NOT_ENTERED = 0; uint256 private constant _ENTERED = 1; /// Modifiers /// modifier nonReentrant() { ReentrancyStorage storage s = reentrancyStorage(); if (s.status == _ENTERED) revert ReentrancyError(); s.status = _ENTERED; _; s.status = _NOT_ENTERED; } /// Private Methods /// /// @dev fetch local storage function reentrancyStorage() private pure returns (ReentrancyStorage storage data) { bytes32 position = NAMESPACE; // solhint-disable-next-line no-inline-assembly assembly { data.slot := position } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import { ILiFi } from "../Interfaces/ILiFi.sol"; import { LibSwap } from "../Libraries/LibSwap.sol"; import { LibAsset } from "../Libraries/LibAsset.sol"; import { LibAllowList } from "../Libraries/LibAllowList.sol"; import { ContractCallNotAllowed, NoSwapDataProvided, CumulativeSlippageTooHigh } from "../Errors/GenericErrors.sol"; /// @title Swapper /// @author LI.FI (https://li.fi) /// @notice Abstract contract to provide swap functionality contract SwapperV2 is ILiFi { /// Types /// /// @dev only used to get around "Stack Too Deep" errors struct ReserveData { bytes32 transactionId; address payable leftoverReceiver; uint256 nativeReserve; } /// Modifiers /// /// @dev Sends any leftover balances back to the user /// @notice Sends any leftover balances to the user /// @param _swaps Swap data array /// @param _leftoverReceiver Address to send leftover tokens to /// @param _initialBalances Array of initial token balances modifier noLeftovers( LibSwap.SwapData[] calldata _swaps, address payable _leftoverReceiver, uint256[] memory _initialBalances ) { uint256 numSwaps = _swaps.length; if (numSwaps != 1) { address finalAsset = _swaps[numSwaps - 1].receivingAssetId; uint256 curBalance; _; for (uint256 i = 0; i < numSwaps - 1; ) { address curAsset = _swaps[i].receivingAssetId; // Handle multi-to-one swaps if (curAsset != finalAsset) { curBalance = LibAsset.getOwnBalance(curAsset) - _initialBalances[i]; if (curBalance > 0) { LibAsset.transferAsset( curAsset, _leftoverReceiver, curBalance ); } } unchecked { ++i; } } } else { _; } } /// @dev Sends any leftover balances back to the user reserving native tokens /// @notice Sends any leftover balances to the user /// @param _swaps Swap data array /// @param _leftoverReceiver Address to send leftover tokens to /// @param _initialBalances Array of initial token balances modifier noLeftoversReserve( LibSwap.SwapData[] calldata _swaps, address payable _leftoverReceiver, uint256[] memory _initialBalances, uint256 _nativeReserve ) { uint256 numSwaps = _swaps.length; if (numSwaps != 1) { address finalAsset = _swaps[numSwaps - 1].receivingAssetId; uint256 curBalance; _; for (uint256 i = 0; i < numSwaps - 1; ) { address curAsset = _swaps[i].receivingAssetId; // Handle multi-to-one swaps if (curAsset != finalAsset) { curBalance = LibAsset.getOwnBalance(curAsset) - _initialBalances[i]; uint256 reserve = LibAsset.isNativeAsset(curAsset) ? _nativeReserve : 0; if (curBalance > 0) { LibAsset.transferAsset( curAsset, _leftoverReceiver, curBalance - reserve ); } } unchecked { ++i; } } } else { _; } } /// @dev Refunds any excess native asset sent to the contract after the main function /// @notice Refunds any excess native asset sent to the contract after the main function /// @param _refundReceiver Address to send refunds to modifier refundExcessNative(address payable _refundReceiver) { uint256 initialBalance = address(this).balance - msg.value; _; uint256 finalBalance = address(this).balance; if (finalBalance > initialBalance) { LibAsset.transferAsset( LibAsset.NATIVE_ASSETID, _refundReceiver, finalBalance - initialBalance ); } } /// Internal Methods /// /// @dev Deposits value, executes swaps, and performs minimum amount check /// @param _transactionId the transaction id associated with the operation /// @param _minAmount the minimum amount of the final asset to receive /// @param _swaps Array of data used to execute swaps /// @param _leftoverReceiver The address to send leftover funds to /// @return uint256 result of the swap function _depositAndSwap( bytes32 _transactionId, uint256 _minAmount, LibSwap.SwapData[] calldata _swaps, address payable _leftoverReceiver ) internal returns (uint256) { uint256 numSwaps = _swaps.length; if (numSwaps == 0) { revert NoSwapDataProvided(); } address finalTokenId = _swaps[numSwaps - 1].receivingAssetId; uint256 initialBalance = LibAsset.getOwnBalance(finalTokenId); if (LibAsset.isNativeAsset(finalTokenId)) { initialBalance -= msg.value; } uint256[] memory initialBalances = _fetchBalances(_swaps); LibAsset.depositAssets(_swaps); _executeSwaps( _transactionId, _swaps, _leftoverReceiver, initialBalances ); uint256 newBalance = LibAsset.getOwnBalance(finalTokenId) - initialBalance; if (newBalance < _minAmount) { revert CumulativeSlippageTooHigh(_minAmount, newBalance); } return newBalance; } /// @dev Deposits value, executes swaps, and performs minimum amount check and reserves native token for fees /// @param _transactionId the transaction id associated with the operation /// @param _minAmount the minimum amount of the final asset to receive /// @param _swaps Array of data used to execute swaps /// @param _leftoverReceiver The address to send leftover funds to /// @param _nativeReserve Amount of native token to prevent from being swept back to the caller function _depositAndSwap( bytes32 _transactionId, uint256 _minAmount, LibSwap.SwapData[] calldata _swaps, address payable _leftoverReceiver, uint256 _nativeReserve ) internal returns (uint256) { uint256 numSwaps = _swaps.length; if (numSwaps == 0) { revert NoSwapDataProvided(); } address finalTokenId = _swaps[numSwaps - 1].receivingAssetId; uint256 initialBalance = LibAsset.getOwnBalance(finalTokenId); if (LibAsset.isNativeAsset(finalTokenId)) { initialBalance -= msg.value; } uint256[] memory initialBalances = _fetchBalances(_swaps); LibAsset.depositAssets(_swaps); ReserveData memory rd = ReserveData( _transactionId, _leftoverReceiver, _nativeReserve ); _executeSwaps(rd, _swaps, initialBalances); uint256 newBalance = LibAsset.getOwnBalance(finalTokenId) - initialBalance; if (LibAsset.isNativeAsset(finalTokenId)) { newBalance -= _nativeReserve; } if (newBalance < _minAmount) { revert CumulativeSlippageTooHigh(_minAmount, newBalance); } return newBalance; } /// Private Methods /// /// @dev Executes swaps and checks that DEXs used are in the allowList /// @param _transactionId the transaction id associated with the operation /// @param _swaps Array of data used to execute swaps /// @param _leftoverReceiver Address to send leftover tokens to /// @param _initialBalances Array of initial balances function _executeSwaps( bytes32 _transactionId, LibSwap.SwapData[] calldata _swaps, address payable _leftoverReceiver, uint256[] memory _initialBalances ) internal noLeftovers(_swaps, _leftoverReceiver, _initialBalances) { uint256 numSwaps = _swaps.length; for (uint256 i = 0; i < numSwaps; ) { LibSwap.SwapData calldata currentSwap = _swaps[i]; if ( !((LibAsset.isNativeAsset(currentSwap.sendingAssetId) || LibAllowList.contractIsAllowed(currentSwap.approveTo)) && LibAllowList.contractIsAllowed(currentSwap.callTo) && LibAllowList.selectorIsAllowed( bytes4(currentSwap.callData[:4]) )) ) revert ContractCallNotAllowed(); LibSwap.swap(_transactionId, currentSwap); unchecked { ++i; } } } /// @dev Executes swaps and checks that DEXs used are in the allowList /// @param _reserveData Data passed used to reserve native tokens /// @param _swaps Array of data used to execute swaps function _executeSwaps( ReserveData memory _reserveData, LibSwap.SwapData[] calldata _swaps, uint256[] memory _initialBalances ) internal noLeftoversReserve( _swaps, _reserveData.leftoverReceiver, _initialBalances, _reserveData.nativeReserve ) { uint256 numSwaps = _swaps.length; for (uint256 i = 0; i < numSwaps; ) { LibSwap.SwapData calldata currentSwap = _swaps[i]; if ( !((LibAsset.isNativeAsset(currentSwap.sendingAssetId) || LibAllowList.contractIsAllowed(currentSwap.approveTo)) && LibAllowList.contractIsAllowed(currentSwap.callTo) && LibAllowList.selectorIsAllowed( bytes4(currentSwap.callData[:4]) )) ) revert ContractCallNotAllowed(); LibSwap.swap(_reserveData.transactionId, currentSwap); unchecked { ++i; } } } /// @dev Fetches balances of tokens to be swapped before swapping. /// @param _swaps Array of data used to execute swaps /// @return uint256[] Array of token balances. function _fetchBalances( LibSwap.SwapData[] calldata _swaps ) private view returns (uint256[] memory) { uint256 numSwaps = _swaps.length; uint256[] memory balances = new uint256[](numSwaps); address asset; for (uint256 i = 0; i < numSwaps; ) { asset = _swaps[i].receivingAssetId; balances[i] = LibAsset.getOwnBalance(asset); if (LibAsset.isNativeAsset(asset)) { balances[i] -= msg.value; } unchecked { ++i; } } return balances; } }
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.17; import { LibAsset } from "../Libraries/LibAsset.sol"; import { LibUtil } from "../Libraries/LibUtil.sol"; import { InvalidReceiver, InformationMismatch, InvalidSendingToken, InvalidAmount, NativeAssetNotSupported, InvalidDestinationChain, CannotBridgeToSameNetwork } from "../Errors/GenericErrors.sol"; import { ILiFi } from "../Interfaces/ILiFi.sol"; import { LibSwap } from "../Libraries/LibSwap.sol"; contract Validatable { modifier validateBridgeData(ILiFi.BridgeData memory _bridgeData) { if (LibUtil.isZeroAddress(_bridgeData.receiver)) { revert InvalidReceiver(); } if (_bridgeData.minAmount == 0) { revert InvalidAmount(); } if (_bridgeData.destinationChainId == block.chainid) { revert CannotBridgeToSameNetwork(); } _; } modifier noNativeAsset(ILiFi.BridgeData memory _bridgeData) { if (LibAsset.isNativeAsset(_bridgeData.sendingAssetId)) { revert NativeAssetNotSupported(); } _; } modifier onlyAllowSourceToken( ILiFi.BridgeData memory _bridgeData, address _token ) { if (_bridgeData.sendingAssetId != _token) { revert InvalidSendingToken(); } _; } modifier onlyAllowDestinationChain( ILiFi.BridgeData memory _bridgeData, uint256 _chainId ) { if (_bridgeData.destinationChainId != _chainId) { revert InvalidDestinationChain(); } _; } modifier containsSourceSwaps(ILiFi.BridgeData memory _bridgeData) { if (!_bridgeData.hasSourceSwaps) { revert InformationMismatch(); } _; } modifier doesNotContainSourceSwaps(ILiFi.BridgeData memory _bridgeData) { if (_bridgeData.hasSourceSwaps) { revert InformationMismatch(); } _; } modifier doesNotContainDestinationCalls( ILiFi.BridgeData memory _bridgeData ) { if (_bridgeData.hasDestinationCall) { revert InformationMismatch(); } _; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.17; // solhint-disable contract-name-camelcase interface IStargateRouter { struct lzTxObj { uint256 dstGasForCall; uint256 dstNativeAmount; bytes dstNativeAddr; } /// @notice SwapAmount struct /// @param amountLD The amount, in Local Decimals, to be swapped /// @param minAmountLD The minimum amount accepted out on destination struct SwapAmount { uint256 amountLD; uint256 minAmountLD; } /// @notice Returns factory address used for creating pools. function factory() external view returns (address); /// @notice Swap assets cross-chain. /// @dev Pass (0, 0, "0x") to lzTxParams /// for 0 additional gasLimit increase, 0 airdrop, at 0x address. /// @param dstChainId Destination chainId /// @param srcPoolId Source pool id /// @param dstPoolId Dest pool id /// @param refundAddress Refund adddress. extra gas (if any) is returned to this address /// @param amountLD Quantity to swap /// @param minAmountLD The min qty you would accept on the destination /// @param lzTxParams Additional gas, airdrop data /// @param to The address to send the tokens to on the destination /// @param payload Additional payload. You can abi.encode() them here function swap( uint16 dstChainId, uint256 srcPoolId, uint256 dstPoolId, address payable refundAddress, uint256 amountLD, uint256 minAmountLD, lzTxObj memory lzTxParams, bytes calldata to, bytes calldata payload ) external payable; /// @notice Swap native assets cross-chain. /// @param _dstChainId Destination Stargate chainId /// @param _refundAddress Refunds additional messageFee to this address /// @param _toAddress The receiver of the destination ETH /// @param _swapAmount The amount and the minimum swap amount /// @param _lzTxParams The LZ tx params /// @param _payload The payload to send to the destination function swapETHAndCall( uint16 _dstChainId, address payable _refundAddress, bytes calldata _toAddress, SwapAmount memory _swapAmount, IStargateRouter.lzTxObj memory _lzTxParams, bytes calldata _payload ) external payable; /// @notice Returns the native gas fee required for swap. function quoteLayerZeroFee( uint16 dstChainId, uint8 functionType, bytes calldata toAddress, bytes calldata transferAndCallPayload, lzTxObj memory lzTxParams ) external view returns (uint256 nativeFee, uint256 zroFee); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import { IDiamondCut } from "../Interfaces/IDiamondCut.sol"; import { LibUtil } from "../Libraries/LibUtil.sol"; import { OnlyContractOwner } from "../Errors/GenericErrors.sol"; /// Implementation of EIP-2535 Diamond Standard /// https://eips.ethereum.org/EIPS/eip-2535 library LibDiamond { bytes32 internal constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); // Diamond specific errors error IncorrectFacetCutAction(); error NoSelectorsInFace(); error FunctionAlreadyExists(); error FacetAddressIsZero(); error FacetAddressIsNotZero(); error FacetContainsNoCode(); error FunctionDoesNotExist(); error FunctionIsImmutable(); error InitZeroButCalldataNotEmpty(); error CalldataEmptyButInitNotZero(); error InitReverted(); // ---------------- struct FacetAddressAndPosition { address facetAddress; uint96 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array } struct FacetFunctionSelectors { bytes4[] functionSelectors; uint256 facetAddressPosition; // position of facetAddress in facetAddresses array } struct DiamondStorage { // maps function selector to the facet address and // the position of the selector in the facetFunctionSelectors.selectors array mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition; // maps facet addresses to function selectors mapping(address => FacetFunctionSelectors) facetFunctionSelectors; // facet addresses address[] facetAddresses; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; // solhint-disable-next-line no-inline-assembly assembly { ds.slot := position } } event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); function setContractOwner(address _newOwner) internal { DiamondStorage storage ds = diamondStorage(); address previousOwner = ds.contractOwner; ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = diamondStorage().contractOwner; } function enforceIsContractOwner() internal view { if (msg.sender != diamondStorage().contractOwner) revert OnlyContractOwner(); } event DiamondCut( IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata ); // Internal function version of diamondCut function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { for (uint256 facetIndex; facetIndex < _diamondCut.length; ) { IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action; if (action == IDiamondCut.FacetCutAction.Add) { addFunctions( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors ); } else if (action == IDiamondCut.FacetCutAction.Replace) { replaceFunctions( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors ); } else if (action == IDiamondCut.FacetCutAction.Remove) { removeFunctions( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors ); } else { revert IncorrectFacetCutAction(); } unchecked { ++facetIndex; } } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addFunctions( address _facetAddress, bytes4[] memory _functionSelectors ) internal { if (_functionSelectors.length == 0) { revert NoSelectorsInFace(); } DiamondStorage storage ds = diamondStorage(); if (LibUtil.isZeroAddress(_facetAddress)) { revert FacetAddressIsZero(); } uint96 selectorPosition = uint96( ds.facetFunctionSelectors[_facetAddress].functionSelectors.length ); // add new facet address if it does not exist if (selectorPosition == 0) { addFacet(ds, _facetAddress); } for ( uint256 selectorIndex; selectorIndex < _functionSelectors.length; ) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds .selectorToFacetAndPosition[selector] .facetAddress; if (!LibUtil.isZeroAddress(oldFacetAddress)) { revert FunctionAlreadyExists(); } addFunction(ds, selector, selectorPosition, _facetAddress); unchecked { ++selectorPosition; ++selectorIndex; } } } function replaceFunctions( address _facetAddress, bytes4[] memory _functionSelectors ) internal { if (_functionSelectors.length == 0) { revert NoSelectorsInFace(); } DiamondStorage storage ds = diamondStorage(); if (LibUtil.isZeroAddress(_facetAddress)) { revert FacetAddressIsZero(); } uint96 selectorPosition = uint96( ds.facetFunctionSelectors[_facetAddress].functionSelectors.length ); // add new facet address if it does not exist if (selectorPosition == 0) { addFacet(ds, _facetAddress); } for ( uint256 selectorIndex; selectorIndex < _functionSelectors.length; ) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds .selectorToFacetAndPosition[selector] .facetAddress; if (oldFacetAddress == _facetAddress) { revert FunctionAlreadyExists(); } removeFunction(ds, oldFacetAddress, selector); addFunction(ds, selector, selectorPosition, _facetAddress); unchecked { ++selectorPosition; ++selectorIndex; } } } function removeFunctions( address _facetAddress, bytes4[] memory _functionSelectors ) internal { if (_functionSelectors.length == 0) { revert NoSelectorsInFace(); } DiamondStorage storage ds = diamondStorage(); // if function does not exist then do nothing and return if (!LibUtil.isZeroAddress(_facetAddress)) { revert FacetAddressIsNotZero(); } for ( uint256 selectorIndex; selectorIndex < _functionSelectors.length; ) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds .selectorToFacetAndPosition[selector] .facetAddress; removeFunction(ds, oldFacetAddress, selector); unchecked { ++selectorIndex; } } } function addFacet( DiamondStorage storage ds, address _facetAddress ) internal { enforceHasContractCode(_facetAddress); ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = ds .facetAddresses .length; ds.facetAddresses.push(_facetAddress); } function addFunction( DiamondStorage storage ds, bytes4 _selector, uint96 _selectorPosition, address _facetAddress ) internal { ds .selectorToFacetAndPosition[_selector] .functionSelectorPosition = _selectorPosition; ds.facetFunctionSelectors[_facetAddress].functionSelectors.push( _selector ); ds.selectorToFacetAndPosition[_selector].facetAddress = _facetAddress; } function removeFunction( DiamondStorage storage ds, address _facetAddress, bytes4 _selector ) internal { if (LibUtil.isZeroAddress(_facetAddress)) { revert FunctionDoesNotExist(); } // an immutable function is a function defined directly in a diamond if (_facetAddress == address(this)) { revert FunctionIsImmutable(); } // replace selector with last selector, then delete last selector uint256 selectorPosition = ds .selectorToFacetAndPosition[_selector] .functionSelectorPosition; uint256 lastSelectorPosition = ds .facetFunctionSelectors[_facetAddress] .functionSelectors .length - 1; // if not the same then replace _selector with lastSelector if (selectorPosition != lastSelectorPosition) { bytes4 lastSelector = ds .facetFunctionSelectors[_facetAddress] .functionSelectors[lastSelectorPosition]; ds.facetFunctionSelectors[_facetAddress].functionSelectors[ selectorPosition ] = lastSelector; ds .selectorToFacetAndPosition[lastSelector] .functionSelectorPosition = uint96(selectorPosition); } // delete the last selector ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector]; // if no more selectors for facet address then delete the facet address if (lastSelectorPosition == 0) { // replace facet address with last facet address and delete last facet address uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; uint256 facetAddressPosition = ds .facetFunctionSelectors[_facetAddress] .facetAddressPosition; if (facetAddressPosition != lastFacetAddressPosition) { address lastFacetAddress = ds.facetAddresses[ lastFacetAddressPosition ]; ds.facetAddresses[facetAddressPosition] = lastFacetAddress; ds .facetFunctionSelectors[lastFacetAddress] .facetAddressPosition = facetAddressPosition; } ds.facetAddresses.pop(); delete ds .facetFunctionSelectors[_facetAddress] .facetAddressPosition; } } function initializeDiamondCut( address _init, bytes memory _calldata ) internal { if (LibUtil.isZeroAddress(_init)) { if (_calldata.length != 0) { revert InitZeroButCalldataNotEmpty(); } } else { if (_calldata.length == 0) { revert CalldataEmptyButInitNotZero(); } if (_init != address(this)) { enforceHasContractCode(_init); } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert InitReverted(); } } } } function enforceHasContractCode(address _contract) internal view { uint256 contractSize; // solhint-disable-next-line no-inline-assembly assembly { contractSize := extcodesize(_contract) } if (contractSize == 0) { revert FacetContainsNoCode(); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/IERC20Permit.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; /** * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } /** * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. */ function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } /** * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value)); } /** * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value)); } } /** * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to * 0 before setting it to a non-zero value. */ function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, approvalCall); } } /** * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`. * Revert on invalid signature. */ function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false // and not revert is the subcall reverts. (bool success, bytes memory returndata) = address(token).call(data); return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token)); } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { address recoveredAddress = ecrecover( keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ), owner, spender, value, nonces[owner]++, deadline ) ) ) ), v, r, s ); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } }
// SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../interfaces/IBridge.sol"; import "../../interfaces/IOriginalTokenVault.sol"; import "../../interfaces/IOriginalTokenVaultV2.sol"; import "../../interfaces/IPeggedTokenBridge.sol"; import "../../interfaces/IPeggedTokenBridgeV2.sol"; import "../interfaces/IMessageBus.sol"; import "./MsgDataTypes.sol"; library MessageSenderLib { using SafeERC20 for IERC20; // ============== Internal library functions called by apps ============== /** * @notice Sends a message to an app on another chain via MessageBus without an associated transfer. * @param _receiver The address of the destination app contract. * @param _dstChainId The destination chain ID. * @param _message Arbitrary message bytes to be decoded by the destination app contract. * @param _messageBus The address of the MessageBus on this chain. * @param _fee The fee amount to pay to MessageBus. */ function sendMessage( address _receiver, uint64 _dstChainId, bytes memory _message, address _messageBus, uint256 _fee ) internal { IMessageBus(_messageBus).sendMessage{value: _fee}(_receiver, _dstChainId, _message); } // Send message to non-evm chain with bytes for receiver address, // otherwise same as above. function sendMessage( bytes calldata _receiver, uint64 _dstChainId, bytes memory _message, address _messageBus, uint256 _fee ) internal { IMessageBus(_messageBus).sendMessage{value: _fee}(_receiver, _dstChainId, _message); } /** * @notice Sends a message to an app on another chain via MessageBus with an associated transfer. * @param _receiver The address of the destination app contract. * @param _token The address of the token to be sent. * @param _amount The amount of tokens to be sent. * @param _dstChainId The destination chain ID. * @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice. * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%. * Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least (100% - max slippage percentage) * amount or the * transfer can be refunded. Only applicable to the {MsgDataTypes.BridgeSendType.Liquidity}. * @param _message Arbitrary message bytes to be decoded by the destination app contract. * @param _bridgeSendType One of the {MsgDataTypes.BridgeSendType} enum. * @param _messageBus The address of the MessageBus on this chain. * @param _fee The fee amount to pay to MessageBus. * @return The transfer ID. */ function sendMessageWithTransfer( address _receiver, address _token, uint256 _amount, uint64 _dstChainId, uint64 _nonce, uint32 _maxSlippage, bytes memory _message, MsgDataTypes.BridgeSendType _bridgeSendType, address _messageBus, uint256 _fee ) internal returns (bytes32) { (bytes32 transferId, address bridge) = sendTokenTransfer( _receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage, _bridgeSendType, _messageBus ); if (_message.length > 0) { IMessageBus(_messageBus).sendMessageWithTransfer{value: _fee}( _receiver, _dstChainId, bridge, transferId, _message ); } return transferId; } /** * @notice Sends a token transfer via a bridge. * @param _receiver The address of the destination app contract. * @param _token The address of the token to be sent. * @param _amount The amount of tokens to be sent. * @param _dstChainId The destination chain ID. * @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice. * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%. * Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least (100% - max slippage percentage) * amount or the * transfer can be refunded. * @param _bridgeSendType One of the {MsgDataTypes.BridgeSendType} enum. */ function sendTokenTransfer( address _receiver, address _token, uint256 _amount, uint64 _dstChainId, uint64 _nonce, uint32 _maxSlippage, MsgDataTypes.BridgeSendType _bridgeSendType, address _messageBus ) internal returns (bytes32 transferId, address bridge) { if (_bridgeSendType == MsgDataTypes.BridgeSendType.Liquidity) { bridge = IMessageBus(_messageBus).liquidityBridge(); IERC20(_token).safeIncreaseAllowance(bridge, _amount); IBridge(bridge).send(_receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage); transferId = computeLiqBridgeTransferId(_receiver, _token, _amount, _dstChainId, _nonce); } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegDeposit) { bridge = IMessageBus(_messageBus).pegVault(); IERC20(_token).safeIncreaseAllowance(bridge, _amount); IOriginalTokenVault(bridge).deposit(_token, _amount, _dstChainId, _receiver, _nonce); transferId = computePegV1DepositId(_receiver, _token, _amount, _dstChainId, _nonce); } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegBurn) { bridge = IMessageBus(_messageBus).pegBridge(); IERC20(_token).safeIncreaseAllowance(bridge, _amount); IPeggedTokenBridge(bridge).burn(_token, _amount, _receiver, _nonce); // handle cases where certain tokens do not spend allowance for role-based burn IERC20(_token).safeApprove(bridge, 0); transferId = computePegV1BurnId(_receiver, _token, _amount, _nonce); } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegV2Deposit) { bridge = IMessageBus(_messageBus).pegVaultV2(); IERC20(_token).safeIncreaseAllowance(bridge, _amount); transferId = IOriginalTokenVaultV2(bridge).deposit(_token, _amount, _dstChainId, _receiver, _nonce); } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegV2Burn) { bridge = IMessageBus(_messageBus).pegBridgeV2(); IERC20(_token).safeIncreaseAllowance(bridge, _amount); transferId = IPeggedTokenBridgeV2(bridge).burn(_token, _amount, _dstChainId, _receiver, _nonce); // handle cases where certain tokens do not spend allowance for role-based burn IERC20(_token).safeApprove(bridge, 0); } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegV2BurnFrom) { bridge = IMessageBus(_messageBus).pegBridgeV2(); IERC20(_token).safeIncreaseAllowance(bridge, _amount); transferId = IPeggedTokenBridgeV2(bridge).burnFrom(_token, _amount, _dstChainId, _receiver, _nonce); // handle cases where certain tokens do not spend allowance for role-based burn IERC20(_token).safeApprove(bridge, 0); } else { revert("bridge type not supported"); } } function computeLiqBridgeTransferId( address _receiver, address _token, uint256 _amount, uint64 _dstChainId, uint64 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked(address(this), _receiver, _token, _amount, _dstChainId, _nonce, uint64(block.chainid)) ); } function computePegV1DepositId( address _receiver, address _token, uint256 _amount, uint64 _dstChainId, uint64 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked(address(this), _token, _amount, _dstChainId, _receiver, _nonce, uint64(block.chainid)) ); } function computePegV1BurnId( address _receiver, address _token, uint256 _amount, uint64 _nonce ) internal view returns (bytes32) { return keccak256(abi.encodePacked(address(this), _token, _amount, _receiver, _nonce, uint64(block.chainid))); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { LibSwap } from "../Libraries/LibSwap.sol"; import { ContractCallNotAllowed, ExternalCallFailed, InvalidConfig, UnAuthorized, WithdrawFailed } from "../Errors/GenericErrors.sol"; import { LibAsset } from "../Libraries/LibAsset.sol"; import { LibUtil } from "../Libraries/LibUtil.sol"; import { ILiFi } from "../Interfaces/ILiFi.sol"; import { PeripheryRegistryFacet } from "../Facets/PeripheryRegistryFacet.sol"; import { IExecutor } from "../Interfaces/IExecutor.sol"; import { TransferrableOwnership } from "../Helpers/TransferrableOwnership.sol"; import { IMessageReceiverApp } from "celer-network/contracts/message/interfaces/IMessageReceiverApp.sol"; import { CelerIM } from "lifi/Helpers/CelerIMFacetBase.sol"; import { MessageSenderLib, MsgDataTypes, IMessageBus, IOriginalTokenVault, IPeggedTokenBridge, IOriginalTokenVaultV2, IPeggedTokenBridgeV2 } from "celer-network/contracts/message/libraries/MessageSenderLib.sol"; import { IBridge as ICBridge } from "celer-network/contracts/interfaces/IBridge.sol"; /// @title RelayerCelerIM /// @author LI.FI (https://li.fi) /// @notice Relayer contract for CelerIM that forwards calls and handles refunds on src side and acts receiver on dest /// @custom:version 2.0.0 contract RelayerCelerIM is ILiFi, TransferrableOwnership { using SafeERC20 for IERC20; /// Storage /// IMessageBus public cBridgeMessageBus; address public diamondAddress; /// Events /// event LogWithdraw( address indexed _assetAddress, address indexed _to, uint256 amount ); /// Modifiers /// modifier onlyCBridgeMessageBus() { if (msg.sender != address(cBridgeMessageBus)) revert UnAuthorized(); _; } modifier onlyDiamond() { if (msg.sender != diamondAddress) revert UnAuthorized(); _; } /// Constructor constructor( address _cBridgeMessageBusAddress, address _owner, address _diamondAddress ) TransferrableOwnership(_owner) { owner = _owner; cBridgeMessageBus = IMessageBus(_cBridgeMessageBusAddress); diamondAddress = _diamondAddress; } /// External Methods /// /** * @notice Called by MessageBus to execute a message with an associated token transfer. * The Receiver is guaranteed to have received the right amount of tokens before this function is called. * @param * (unused) The address of the source app contract * @param _token The address of the token that comes out of the bridge * @param _amount The amount of tokens received at this contract through the cross-chain bridge. * @param * (unused) The source chain ID where the transfer is originated from * @param _message Arbitrary message bytes originated from and encoded by the source app contract * @param * (unused) Address who called the MessageBus execution function */ function executeMessageWithTransfer( address, address _token, uint256 _amount, uint64, bytes calldata _message, address ) external payable onlyCBridgeMessageBus returns (IMessageReceiverApp.ExecutionStatus) { // decode message ( bytes32 transactionId, LibSwap.SwapData[] memory swapData, address receiver, address refundAddress ) = abi.decode( _message, (bytes32, LibSwap.SwapData[], address, address) ); _swapAndCompleteBridgeTokens( transactionId, swapData, _token, payable(receiver), _amount, refundAddress ); return IMessageReceiverApp.ExecutionStatus.Success; } /** * @notice Called by MessageBus to process refund of the original transfer from this contract. * The contract is guaranteed to have received the refund before this function is called. * @param _token The token address of the original transfer * @param _amount The amount of the original transfer * @param _message The same message associated with the original transfer * @param * (unused) Address who called the MessageBus execution function */ function executeMessageWithTransferRefund( address _token, uint256 _amount, bytes calldata _message, address ) external payable onlyCBridgeMessageBus returns (IMessageReceiverApp.ExecutionStatus) { (bytes32 transactionId, , , address refundAddress) = abi.decode( _message, (bytes32, LibSwap.SwapData[], address, address) ); // return funds to cBridgeData.refundAddress LibAsset.transferAsset(_token, payable(refundAddress), _amount); emit LiFiTransferRecovered( transactionId, _token, refundAddress, _amount, block.timestamp ); return IMessageReceiverApp.ExecutionStatus.Success; } /** * @notice Forwards a call to transfer tokens to cBridge (sent via this contract to ensure that potential refunds are sent here) * @param _bridgeData the core information needed for bridging * @param _celerIMData data specific to CelerIM */ // solhint-disable-next-line code-complexity function sendTokenTransfer( ILiFi.BridgeData memory _bridgeData, CelerIM.CelerIMData calldata _celerIMData ) external payable onlyDiamond returns (bytes32 transferId, address bridgeAddress) { // approve to and call correct bridge depending on BridgeSendType // @dev copied and slightly adapted from Celer MessageSenderLib if (_celerIMData.bridgeType == MsgDataTypes.BridgeSendType.Liquidity) { bridgeAddress = cBridgeMessageBus.liquidityBridge(); if (LibAsset.isNativeAsset(_bridgeData.sendingAssetId)) { // case: native asset bridging ICBridge(bridgeAddress).sendNative{ value: _bridgeData.minAmount }( _bridgeData.receiver, _bridgeData.minAmount, uint64(_bridgeData.destinationChainId), _celerIMData.nonce, _celerIMData.maxSlippage ); } else { // case: ERC20 asset bridging LibAsset.maxApproveERC20( IERC20(_bridgeData.sendingAssetId), bridgeAddress, _bridgeData.minAmount ); // solhint-disable-next-line check-send-result ICBridge(bridgeAddress).send( _bridgeData.receiver, _bridgeData.sendingAssetId, _bridgeData.minAmount, uint64(_bridgeData.destinationChainId), _celerIMData.nonce, _celerIMData.maxSlippage ); } transferId = MessageSenderLib.computeLiqBridgeTransferId( _bridgeData.receiver, _bridgeData.sendingAssetId, _bridgeData.minAmount, uint64(_bridgeData.destinationChainId), _celerIMData.nonce ); } else if ( _celerIMData.bridgeType == MsgDataTypes.BridgeSendType.PegDeposit ) { bridgeAddress = cBridgeMessageBus.pegVault(); LibAsset.maxApproveERC20( IERC20(_bridgeData.sendingAssetId), bridgeAddress, _bridgeData.minAmount ); IOriginalTokenVault(bridgeAddress).deposit( _bridgeData.sendingAssetId, _bridgeData.minAmount, uint64(_bridgeData.destinationChainId), _bridgeData.receiver, _celerIMData.nonce ); transferId = MessageSenderLib.computePegV1DepositId( _bridgeData.receiver, _bridgeData.sendingAssetId, _bridgeData.minAmount, uint64(_bridgeData.destinationChainId), _celerIMData.nonce ); } else if ( _celerIMData.bridgeType == MsgDataTypes.BridgeSendType.PegBurn ) { bridgeAddress = cBridgeMessageBus.pegBridge(); LibAsset.maxApproveERC20( IERC20(_bridgeData.sendingAssetId), bridgeAddress, _bridgeData.minAmount ); IPeggedTokenBridge(bridgeAddress).burn( _bridgeData.sendingAssetId, _bridgeData.minAmount, _bridgeData.receiver, _celerIMData.nonce ); transferId = MessageSenderLib.computePegV1BurnId( _bridgeData.receiver, _bridgeData.sendingAssetId, _bridgeData.minAmount, _celerIMData.nonce ); } else if ( _celerIMData.bridgeType == MsgDataTypes.BridgeSendType.PegV2Deposit ) { bridgeAddress = cBridgeMessageBus.pegVaultV2(); if (LibAsset.isNativeAsset(_bridgeData.sendingAssetId)) { // case: native asset bridging transferId = IOriginalTokenVaultV2(bridgeAddress) .depositNative{ value: _bridgeData.minAmount }( _bridgeData.minAmount, uint64(_bridgeData.destinationChainId), _bridgeData.receiver, _celerIMData.nonce ); } else { // case: ERC20 bridging LibAsset.maxApproveERC20( IERC20(_bridgeData.sendingAssetId), bridgeAddress, _bridgeData.minAmount ); transferId = IOriginalTokenVaultV2(bridgeAddress).deposit( _bridgeData.sendingAssetId, _bridgeData.minAmount, uint64(_bridgeData.destinationChainId), _bridgeData.receiver, _celerIMData.nonce ); } } else if ( _celerIMData.bridgeType == MsgDataTypes.BridgeSendType.PegV2Burn ) { bridgeAddress = cBridgeMessageBus.pegBridgeV2(); LibAsset.maxApproveERC20( IERC20(_bridgeData.sendingAssetId), bridgeAddress, _bridgeData.minAmount ); transferId = IPeggedTokenBridgeV2(bridgeAddress).burn( _bridgeData.sendingAssetId, _bridgeData.minAmount, uint64(_bridgeData.destinationChainId), _bridgeData.receiver, _celerIMData.nonce ); } else if ( _celerIMData.bridgeType == MsgDataTypes.BridgeSendType.PegV2BurnFrom ) { bridgeAddress = cBridgeMessageBus.pegBridgeV2(); LibAsset.maxApproveERC20( IERC20(_bridgeData.sendingAssetId), bridgeAddress, _bridgeData.minAmount ); transferId = IPeggedTokenBridgeV2(bridgeAddress).burnFrom( _bridgeData.sendingAssetId, _bridgeData.minAmount, uint64(_bridgeData.destinationChainId), _bridgeData.receiver, _celerIMData.nonce ); } else { revert InvalidConfig(); } } /** * @notice Forwards a call to the CBridge Messagebus * @param _receiver The address of the destination app contract. * @param _dstChainId The destination chain ID. * @param _srcBridge The bridge contract to send the transfer with. * @param _srcTransferId The transfer ID. * @param _dstChainId The destination chain ID. * @param _message Arbitrary message bytes to be decoded by the destination app contract. */ function forwardSendMessageWithTransfer( address _receiver, uint256 _dstChainId, address _srcBridge, bytes32 _srcTransferId, bytes calldata _message ) external payable onlyDiamond { cBridgeMessageBus.sendMessageWithTransfer{ value: msg.value }( _receiver, _dstChainId, _srcBridge, _srcTransferId, _message ); } // ------------------------------------------------------------------------------------------------ /// Private Methods /// /// @notice Performs a swap before completing a cross-chain transaction /// @param _transactionId the transaction id associated with the operation /// @param _swapData array of data needed for swaps /// @param assetId token received from the other chain /// @param receiver address that will receive tokens in the end /// @param amount amount of token function _swapAndCompleteBridgeTokens( bytes32 _transactionId, LibSwap.SwapData[] memory _swapData, address assetId, address payable receiver, uint256 amount, address refundAddress ) private { bool success; IExecutor executor = IExecutor( PeripheryRegistryFacet(diamondAddress).getPeripheryContract( "Executor" ) ); if (LibAsset.isNativeAsset(assetId)) { try executor.swapAndCompleteBridgeTokens{ value: amount }( _transactionId, _swapData, assetId, receiver ) { success = true; } catch { // solhint-disable-next-line avoid-low-level-calls (bool fundsSent, ) = refundAddress.call{ value: amount }(""); if (!fundsSent) { revert ExternalCallFailed(); } } } else { IERC20 token = IERC20(assetId); token.safeApprove(address(executor), 0); token.safeIncreaseAllowance(address(executor), amount); try executor.swapAndCompleteBridgeTokens( _transactionId, _swapData, assetId, receiver ) { success = true; } catch { token.safeTransfer(refundAddress, amount); } token.safeApprove(address(executor), 0); } if (!success) { emit LiFiTransferRecovered( _transactionId, assetId, refundAddress, amount, block.timestamp ); } } /// @notice Sends remaining token to given receiver address (for refund cases) /// @param assetId Address of the token to be withdrawn /// @param receiver Address that will receive tokens /// @param amount Amount of tokens to be withdrawn function withdraw( address assetId, address payable receiver, uint256 amount ) external onlyOwner { if (LibAsset.isNativeAsset(assetId)) { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = receiver.call{ value: amount }(""); if (!success) { revert WithdrawFailed(); } } else { IERC20(assetId).safeTransfer(receiver, amount); } emit LogWithdraw(assetId, receiver, amount); } /// @notice Triggers a cBridge refund with calldata produced by cBridge API /// @param _callTo The address to execute the calldata on /// @param _callData The data to execute /// @param _assetAddress Asset to be withdrawn /// @param _to Address to withdraw to /// @param _amount Amount of asset to withdraw function triggerRefund( address payable _callTo, bytes calldata _callData, address _assetAddress, address _to, uint256 _amount ) external onlyOwner { bool success; // make sure that callTo address is either of the cBridge addresses if ( cBridgeMessageBus.liquidityBridge() != _callTo && cBridgeMessageBus.pegBridge() != _callTo && cBridgeMessageBus.pegBridgeV2() != _callTo && cBridgeMessageBus.pegVault() != _callTo && cBridgeMessageBus.pegVaultV2() != _callTo ) { revert ContractCallNotAllowed(); } // call contract // solhint-disable-next-line avoid-low-level-calls (success, ) = _callTo.call(_callData); // forward funds to _to address and emit event, if cBridge refund successful if (success) { address sendTo = (LibUtil.isZeroAddress(_to)) ? msg.sender : _to; LibAsset.transferAsset(_assetAddress, payable(sendTo), _amount); emit LogWithdraw(_assetAddress, sendTo, _amount); } else { revert WithdrawFailed(); } } // required in order to receive native tokens from cBridge facet // solhint-disable-next-line no-empty-blocks receive() external payable {} }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import { InvalidContract } from "../Errors/GenericErrors.sol"; /// @title Lib Allow List /// @author LI.FI (https://li.fi) /// @notice Library for managing and accessing the conract address allow list library LibAllowList { /// Storage /// bytes32 internal constant NAMESPACE = keccak256("com.lifi.library.allow.list"); struct AllowListStorage { mapping(address => bool) allowlist; mapping(bytes4 => bool) selectorAllowList; address[] contracts; } /// @dev Adds a contract address to the allow list /// @param _contract the contract address to add function addAllowedContract(address _contract) internal { _checkAddress(_contract); AllowListStorage storage als = _getStorage(); if (als.allowlist[_contract]) return; als.allowlist[_contract] = true; als.contracts.push(_contract); } /// @dev Checks whether a contract address has been added to the allow list /// @param _contract the contract address to check function contractIsAllowed( address _contract ) internal view returns (bool) { return _getStorage().allowlist[_contract]; } /// @dev Remove a contract address from the allow list /// @param _contract the contract address to remove function removeAllowedContract(address _contract) internal { AllowListStorage storage als = _getStorage(); if (!als.allowlist[_contract]) { return; } als.allowlist[_contract] = false; uint256 length = als.contracts.length; // Find the contract in the list for (uint256 i = 0; i < length; i++) { if (als.contracts[i] == _contract) { // Move the last element into the place to delete als.contracts[i] = als.contracts[length - 1]; // Remove the last element als.contracts.pop(); break; } } } /// @dev Fetch contract addresses from the allow list function getAllowedContracts() internal view returns (address[] memory) { return _getStorage().contracts; } /// @dev Add a selector to the allow list /// @param _selector the selector to add function addAllowedSelector(bytes4 _selector) internal { _getStorage().selectorAllowList[_selector] = true; } /// @dev Removes a selector from the allow list /// @param _selector the selector to remove function removeAllowedSelector(bytes4 _selector) internal { _getStorage().selectorAllowList[_selector] = false; } /// @dev Returns if selector has been added to the allow list /// @param _selector the selector to check function selectorIsAllowed(bytes4 _selector) internal view returns (bool) { return _getStorage().selectorAllowList[_selector]; } /// @dev Fetch local storage struct function _getStorage() internal pure returns (AllowListStorage storage als) { bytes32 position = NAMESPACE; // solhint-disable-next-line no-inline-assembly assembly { als.slot := position } } /// @dev Contains business logic for validating a contract address. /// @param _contract address of the dex to check function _checkAddress(address _contract) private view { if (_contract == address(0)) revert InvalidContract(); if (_contract.code.length == 0) revert InvalidContract(); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; interface IDiamondCut { enum FacetCutAction { Add, Replace, Remove } // Add=0, Replace=1, Remove=2 struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * * Furthermore, `isContract` will also return true if the target contract within * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, * which only has an effect at the end of a transaction. * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.8.0; interface IBridge { function send( address _receiver, address _token, uint256 _amount, uint64 _dstChainId, uint64 _nonce, uint32 _maxSlippage ) external; function sendNative( address _receiver, uint256 _amount, uint64 _dstChainId, uint64 _nonce, uint32 _maxSlippage ) external payable; function relay( bytes calldata _relayRequest, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external; function transfers(bytes32 transferId) external view returns (bool); function withdraws(bytes32 withdrawId) external view returns (bool); function withdraw( bytes calldata _wdmsg, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external; /** * @notice Verifies that a message is signed by a quorum among the signers. * @param _msg signed message * @param _sigs list of signatures sorted by signer addresses in ascending order * @param _signers sorted list of current signers * @param _powers powers of current signers */ function verifySigs( bytes memory _msg, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external view; }
// SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.8.0; interface IOriginalTokenVault { /** * @notice Lock original tokens to trigger mint at a remote chain's PeggedTokenBridge * @param _token local token address * @param _amount locked token amount * @param _mintChainId destination chainId to mint tokens * @param _mintAccount destination account to receive minted tokens * @param _nonce user input to guarantee unique depositId */ function deposit( address _token, uint256 _amount, uint64 _mintChainId, address _mintAccount, uint64 _nonce ) external; /** * @notice Lock native token as original token to trigger mint at a remote chain's PeggedTokenBridge * @param _amount locked token amount * @param _mintChainId destination chainId to mint tokens * @param _mintAccount destination account to receive minted tokens * @param _nonce user input to guarantee unique depositId */ function depositNative( uint256 _amount, uint64 _mintChainId, address _mintAccount, uint64 _nonce ) external payable; /** * @notice Withdraw locked original tokens triggered by a burn at a remote chain's PeggedTokenBridge. * @param _request The serialized Withdraw protobuf. * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by * +2/3 of the bridge's current signing power to be delivered. * @param _signers The sorted list of signers. * @param _powers The signing powers of the signers. */ function withdraw( bytes calldata _request, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external; function records(bytes32 recordId) external view returns (bool); }
// SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.8.0; interface IOriginalTokenVaultV2 { /** * @notice Lock original tokens to trigger mint at a remote chain's PeggedTokenBridge * @param _token local token address * @param _amount locked token amount * @param _mintChainId destination chainId to mint tokens * @param _mintAccount destination account to receive minted tokens * @param _nonce user input to guarantee unique depositId */ function deposit( address _token, uint256 _amount, uint64 _mintChainId, address _mintAccount, uint64 _nonce ) external returns (bytes32); /** * @notice Lock native token as original token to trigger mint at a remote chain's PeggedTokenBridge * @param _amount locked token amount * @param _mintChainId destination chainId to mint tokens * @param _mintAccount destination account to receive minted tokens * @param _nonce user input to guarantee unique depositId */ function depositNative( uint256 _amount, uint64 _mintChainId, address _mintAccount, uint64 _nonce ) external payable returns (bytes32); /** * @notice Withdraw locked original tokens triggered by a burn at a remote chain's PeggedTokenBridge. * @param _request The serialized Withdraw protobuf. * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by * +2/3 of the bridge's current signing power to be delivered. * @param _signers The sorted list of signers. * @param _powers The signing powers of the signers. */ function withdraw( bytes calldata _request, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external returns (bytes32); function records(bytes32 recordId) external view returns (bool); }
// SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.8.0; interface IPeggedTokenBridge { /** * @notice Burn tokens to trigger withdrawal at a remote chain's OriginalTokenVault * @param _token local token address * @param _amount locked token amount * @param _withdrawAccount account who withdraw original tokens on the remote chain * @param _nonce user input to guarantee unique depositId */ function burn( address _token, uint256 _amount, address _withdrawAccount, uint64 _nonce ) external; /** * @notice Mint tokens triggered by deposit at a remote chain's OriginalTokenVault. * @param _request The serialized Mint protobuf. * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by * +2/3 of the sigsVerifier's current signing power to be delivered. * @param _signers The sorted list of signers. * @param _powers The signing powers of the signers. */ function mint( bytes calldata _request, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external; function records(bytes32 recordId) external view returns (bool); }
// SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.8.0; interface IPeggedTokenBridgeV2 { /** * @notice Burn pegged tokens to trigger a cross-chain withdrawal of the original tokens at a remote chain's * OriginalTokenVault, or mint at another remote chain * @param _token The pegged token address. * @param _amount The amount to burn. * @param _toChainId If zero, withdraw from original vault; otherwise, the remote chain to mint tokens. * @param _toAccount The account to receive tokens on the remote chain * @param _nonce A number to guarantee unique depositId. Can be timestamp in practice. */ function burn( address _token, uint256 _amount, uint64 _toChainId, address _toAccount, uint64 _nonce ) external returns (bytes32); // same with `burn` above, use openzeppelin ERC20Burnable interface function burnFrom( address _token, uint256 _amount, uint64 _toChainId, address _toAccount, uint64 _nonce ) external returns (bytes32); /** * @notice Mint tokens triggered by deposit at a remote chain's OriginalTokenVault. * @param _request The serialized Mint protobuf. * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by * +2/3 of the sigsVerifier's current signing power to be delivered. * @param _signers The sorted list of signers. * @param _powers The signing powers of the signers. */ function mint( bytes calldata _request, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external returns (bytes32); function records(bytes32 recordId) external view returns (bool); }
// SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.8.0; import "../libraries/MsgDataTypes.sol"; interface IMessageBus { /** * @notice Send a message to a contract on another chain. * Sender needs to make sure the uniqueness of the message Id, which is computed as * hash(type.MessageOnly, sender, receiver, srcChainId, srcTxHash, dstChainId, message). * If messages with the same Id are sent, only one of them will succeed at dst chain.. * A fee is charged in the native gas token. * @param _receiver The address of the destination app contract. * @param _dstChainId The destination chain ID. * @param _message Arbitrary message bytes to be decoded by the destination app contract. */ function sendMessage( address _receiver, uint256 _dstChainId, bytes calldata _message ) external payable; // same as above, except that receiver is an non-evm chain address, function sendMessage( bytes calldata _receiver, uint256 _dstChainId, bytes calldata _message ) external payable; /** * @notice Send a message associated with a token transfer to a contract on another chain. * If messages with the same srcTransferId are sent, only one of them will succeed at dst chain.. * A fee is charged in the native token. * @param _receiver The address of the destination app contract. * @param _dstChainId The destination chain ID. * @param _srcBridge The bridge contract to send the transfer with. * @param _srcTransferId The transfer ID. * @param _dstChainId The destination chain ID. * @param _message Arbitrary message bytes to be decoded by the destination app contract. */ function sendMessageWithTransfer( address _receiver, uint256 _dstChainId, address _srcBridge, bytes32 _srcTransferId, bytes calldata _message ) external payable; /** * @notice Execute a message not associated with a transfer. * @param _message Arbitrary message bytes originated from and encoded by the source app contract * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by * +2/3 of the sigsVerifier's current signing power to be delivered. * @param _signers The sorted list of signers. * @param _powers The signing powers of the signers. */ function executeMessage( bytes calldata _message, MsgDataTypes.RouteInfo calldata _route, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external payable; /** * @notice Execute a message with a successful transfer. * @param _message Arbitrary message bytes originated from and encoded by the source app contract * @param _transfer The transfer info. * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by * +2/3 of the sigsVerifier's current signing power to be delivered. * @param _signers The sorted list of signers. * @param _powers The signing powers of the signers. */ function executeMessageWithTransfer( bytes calldata _message, MsgDataTypes.TransferInfo calldata _transfer, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external payable; /** * @notice Execute a message with a refunded transfer. * @param _message Arbitrary message bytes originated from and encoded by the source app contract * @param _transfer The transfer info. * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by * +2/3 of the sigsVerifier's current signing power to be delivered. * @param _signers The sorted list of signers. * @param _powers The signing powers of the signers. */ function executeMessageWithTransferRefund( bytes calldata _message, // the same message associated with the original transfer MsgDataTypes.TransferInfo calldata _transfer, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external payable; /** * @notice Withdraws message fee in the form of native gas token. * @param _account The address receiving the fee. * @param _cumulativeFee The cumulative fee credited to the account. Tracked by SGN. * @param _sigs The list of signatures sorted by signing addresses in ascending order. A withdrawal must be * signed-off by +2/3 of the sigsVerifier's current signing power to be delivered. * @param _signers The sorted list of signers. * @param _powers The signing powers of the signers. */ function withdrawFee( address _account, uint256 _cumulativeFee, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external; /** * @notice Calculates the required fee for the message. * @param _message Arbitrary message bytes to be decoded by the destination app contract. @ @return The required fee. */ function calcFee(bytes calldata _message) external view returns (uint256); function liquidityBridge() external view returns (address); function pegBridge() external view returns (address); function pegBridgeV2() external view returns (address); function pegVault() external view returns (address); function pegVaultV2() external view returns (address); }
// SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.8.0; library MsgDataTypes { string constant ABORT_PREFIX = "MSG::ABORT:"; // bridge operation type at the sender side (src chain) enum BridgeSendType { Null, Liquidity, PegDeposit, PegBurn, PegV2Deposit, PegV2Burn, PegV2BurnFrom } // bridge operation type at the receiver side (dst chain) enum TransferType { Null, LqRelay, // relay through liquidity bridge LqWithdraw, // withdraw from liquidity bridge PegMint, // mint through pegged token bridge PegWithdraw, // withdraw from original token vault PegV2Mint, // mint through pegged token bridge v2 PegV2Withdraw // withdraw from original token vault v2 } enum MsgType { MessageWithTransfer, MessageOnly } enum TxStatus { Null, Success, Fail, Fallback, Pending // transient state within a transaction } struct TransferInfo { TransferType t; address sender; address receiver; address token; uint256 amount; uint64 wdseq; // only needed for LqWithdraw (refund) uint64 srcChainId; bytes32 refId; bytes32 srcTxHash; // src chain msg tx hash } struct RouteInfo { address sender; address receiver; uint64 srcChainId; bytes32 srcTxHash; // src chain msg tx hash } // used for msg from non-evm chains with longer-bytes address struct RouteInfo2 { bytes sender; address receiver; uint64 srcChainId; bytes32 srcTxHash; } // combination of RouteInfo and RouteInfo2 for easier processing struct Route { address sender; // from RouteInfo bytes senderBytes; // from RouteInfo2 address receiver; uint64 srcChainId; bytes32 srcTxHash; } struct MsgWithTransferExecutionParams { bytes message; TransferInfo transfer; bytes[] sigs; address[] signers; uint256[] powers; } struct BridgeTransferParams { bytes request; bytes[] sigs; address[] signers; uint256[] powers; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import { LibDiamond } from "../Libraries/LibDiamond.sol"; /// @title Periphery Registry Facet /// @author LI.FI (https://li.fi) /// @notice A simple registry to track LIFI periphery contracts /// @custom:version 1.0.0 contract PeripheryRegistryFacet { /// Storage /// bytes32 internal constant NAMESPACE = keccak256("com.lifi.facets.periphery_registry"); /// Types /// struct Storage { mapping(string => address) contracts; } /// Events /// event PeripheryContractRegistered(string name, address contractAddress); /// External Methods /// /// @notice Registers a periphery contract address with a specified name /// @param _name the name to register the contract address under /// @param _contractAddress the address of the contract to register function registerPeripheryContract( string calldata _name, address _contractAddress ) external { LibDiamond.enforceIsContractOwner(); Storage storage s = getStorage(); s.contracts[_name] = _contractAddress; emit PeripheryContractRegistered(_name, _contractAddress); } /// @notice Returns the registered contract address by its name /// @param _name the registered name of the contract function getPeripheryContract( string calldata _name ) external view returns (address) { return getStorage().contracts[_name]; } /// @dev fetch local storage function getStorage() private pure returns (Storage storage s) { bytes32 namespace = NAMESPACE; // solhint-disable-next-line no-inline-assembly assembly { s.slot := namespace } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import { LibSwap } from "../Libraries/LibSwap.sol"; /// @title Interface for Executor /// @author LI.FI (https://li.fi) interface IExecutor { /// @notice Performs a swap before completing a cross-chain transaction /// @param _transactionId the transaction id associated with the operation /// @param _swapData array of data needed for swaps /// @param transferredAssetId token received from the other chain /// @param receiver address that will receive tokens in the end function swapAndCompleteBridgeTokens( bytes32 _transactionId, LibSwap.SwapData[] calldata _swapData, address transferredAssetId, address payable receiver ) external payable; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import { IERC173 } from "../Interfaces/IERC173.sol"; import { LibAsset } from "../Libraries/LibAsset.sol"; contract TransferrableOwnership is IERC173 { address public owner; address public pendingOwner; /// Errors /// error UnAuthorized(); error NoNullOwner(); error NewOwnerMustNotBeSelf(); error NoPendingOwnershipTransfer(); error NotPendingOwner(); /// Events /// event OwnershipTransferRequested( address indexed _from, address indexed _to ); constructor(address initialOwner) { owner = initialOwner; } modifier onlyOwner() { if (msg.sender != owner) revert UnAuthorized(); _; } /// @notice Initiates transfer of ownership to a new address /// @param _newOwner the address to transfer ownership to function transferOwnership(address _newOwner) external onlyOwner { if (_newOwner == LibAsset.NULL_ADDRESS) revert NoNullOwner(); if (_newOwner == msg.sender) revert NewOwnerMustNotBeSelf(); pendingOwner = _newOwner; emit OwnershipTransferRequested(msg.sender, pendingOwner); } /// @notice Cancel transfer of ownership function cancelOwnershipTransfer() external onlyOwner { if (pendingOwner == LibAsset.NULL_ADDRESS) revert NoPendingOwnershipTransfer(); pendingOwner = LibAsset.NULL_ADDRESS; } /// @notice Confirms transfer of ownership to the calling address (msg.sender) function confirmOwnershipTransfer() external { address _pendingOwner = pendingOwner; if (msg.sender != _pendingOwner) revert NotPendingOwner(); emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = LibAsset.NULL_ADDRESS; } }
// SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.8.0; interface IMessageReceiverApp { enum ExecutionStatus { Fail, // execution failed, finalized Success, // execution succeeded, finalized Retry // execution rejected, can retry later } /** * @notice Called by MessageBus to execute a message * @param _sender The address of the source app contract * @param _srcChainId The source chain ID where the transfer is originated from * @param _message Arbitrary message bytes originated from and encoded by the source app contract * @param _executor Address who called the MessageBus execution function */ function executeMessage( address _sender, uint64 _srcChainId, bytes calldata _message, address _executor ) external payable returns (ExecutionStatus); // same as above, except that sender is an non-evm chain address, // otherwise same as above. function executeMessage( bytes calldata _sender, uint64 _srcChainId, bytes calldata _message, address _executor ) external payable returns (ExecutionStatus); /** * @notice Called by MessageBus to execute a message with an associated token transfer. * The contract is guaranteed to have received the right amount of tokens before this function is called. * @param _sender The address of the source app contract * @param _token The address of the token that comes out of the bridge * @param _amount The amount of tokens received at this contract through the cross-chain bridge. * @param _srcChainId The source chain ID where the transfer is originated from * @param _message Arbitrary message bytes originated from and encoded by the source app contract * @param _executor Address who called the MessageBus execution function */ function executeMessageWithTransfer( address _sender, address _token, uint256 _amount, uint64 _srcChainId, bytes calldata _message, address _executor ) external payable returns (ExecutionStatus); /** * @notice Only called by MessageBus if * 1. executeMessageWithTransfer reverts, or * 2. executeMessageWithTransfer returns ExecutionStatus.Fail * The contract is guaranteed to have received the right amount of tokens before this function is called. * @param _sender The address of the source app contract * @param _token The address of the token that comes out of the bridge * @param _amount The amount of tokens received at this contract through the cross-chain bridge. * @param _srcChainId The source chain ID where the transfer is originated from * @param _message Arbitrary message bytes originated from and encoded by the source app contract * @param _executor Address who called the MessageBus execution function */ function executeMessageWithTransferFallback( address _sender, address _token, uint256 _amount, uint64 _srcChainId, bytes calldata _message, address _executor ) external payable returns (ExecutionStatus); /** * @notice Called by MessageBus to process refund of the original transfer from this contract. * The contract is guaranteed to have received the refund before this function is called. * @param _token The token address of the original transfer * @param _amount The amount of the original transfer * @param _message The same message associated with the original transfer * @param _executor Address who called the MessageBus execution function */ function executeMessageWithTransferRefund( address _token, uint256 _amount, bytes calldata _message, address _executor ) external payable returns (ExecutionStatus); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.17; /// @title ERC-173 Contract Ownership Standard /// Note: the ERC-165 identifier for this interface is 0x7f5828d0 /* is ERC165 */ interface IERC173 { /// @dev This emits when ownership of a contract changes. event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @notice Get the address of the owner /// @return owner_ The address of the owner. function owner() external view returns (address owner_); /// @notice Set the address of the new owner of the contract /// @dev Set _newOwner to address(0) to renounce any ownership. /// @param _newOwner The address of the new owner of the contract function transferOwnership(address _newOwner) external; }
{ "remappings": [ "@eth-optimism/=node_modules/@hop-protocol/sdk/node_modules/@eth-optimism/", "@uniswap/=node_modules/@uniswap/", "eth-gas-reporter/=node_modules/eth-gas-reporter/", "hardhat/=node_modules/hardhat/", "hardhat-deploy/=node_modules/hardhat-deploy/", "@openzeppelin/=lib/openzeppelin-contracts/", "celer-network/=lib/sgn-v2-contracts/", "create3-factory/=lib/create3-factory/src/", "solmate/=lib/solmate/src/", "ds-test/=lib/ds-test/src/", "forge-std/=lib/forge-std/src/", "lifi/=src/", "test/=test/", "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/", "openzeppelin-contracts/=lib/openzeppelin-contracts/", "openzeppelin/=lib/openzeppelin-contracts/contracts/", "sgn-v2-contracts/=lib/sgn-v2-contracts/contracts/" ], "optimizer": { "enabled": true, "runs": 1000000 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs" }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "london", "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[],"name":"SliceOutOfBounds","type":"error"},{"inputs":[],"name":"SliceOverflow","type":"error"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"extractBridgeData","outputs":[{"components":[{"internalType":"bytes32","name":"transactionId","type":"bytes32"},{"internalType":"string","name":"bridge","type":"string"},{"internalType":"string","name":"integrator","type":"string"},{"internalType":"address","name":"referrer","type":"address"},{"internalType":"address","name":"sendingAssetId","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"minAmount","type":"uint256"},{"internalType":"uint256","name":"destinationChainId","type":"uint256"},{"internalType":"bool","name":"hasSourceSwaps","type":"bool"},{"internalType":"bool","name":"hasDestinationCall","type":"bool"}],"internalType":"struct ILiFi.BridgeData","name":"bridgeData","type":"tuple"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"extractData","outputs":[{"components":[{"internalType":"bytes32","name":"transactionId","type":"bytes32"},{"internalType":"string","name":"bridge","type":"string"},{"internalType":"string","name":"integrator","type":"string"},{"internalType":"address","name":"referrer","type":"address"},{"internalType":"address","name":"sendingAssetId","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"minAmount","type":"uint256"},{"internalType":"uint256","name":"destinationChainId","type":"uint256"},{"internalType":"bool","name":"hasSourceSwaps","type":"bool"},{"internalType":"bool","name":"hasDestinationCall","type":"bool"}],"internalType":"struct ILiFi.BridgeData","name":"bridgeData","type":"tuple"},{"components":[{"internalType":"address","name":"callTo","type":"address"},{"internalType":"address","name":"approveTo","type":"address"},{"internalType":"address","name":"sendingAssetId","type":"address"},{"internalType":"address","name":"receivingAssetId","type":"address"},{"internalType":"uint256","name":"fromAmount","type":"uint256"},{"internalType":"bytes","name":"callData","type":"bytes"},{"internalType":"bool","name":"requiresDeposit","type":"bool"}],"internalType":"struct LibSwap.SwapData[]","name":"swapData","type":"tuple[]"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"extractGenericSwapParameters","outputs":[{"internalType":"address","name":"sendingAssetId","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"receivingAssetId","type":"address"},{"internalType":"uint256","name":"receivingAmount","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"extractMainParameters","outputs":[{"internalType":"string","name":"bridge","type":"string"},{"internalType":"address","name":"sendingAssetId","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"destinationChainId","type":"uint256"},{"internalType":"bool","name":"hasSourceSwaps","type":"bool"},{"internalType":"bool","name":"hasDestinationCall","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"extractSwapData","outputs":[{"components":[{"internalType":"address","name":"callTo","type":"address"},{"internalType":"address","name":"approveTo","type":"address"},{"internalType":"address","name":"sendingAssetId","type":"address"},{"internalType":"address","name":"receivingAssetId","type":"address"},{"internalType":"uint256","name":"fromAmount","type":"uint256"},{"internalType":"bytes","name":"callData","type":"bytes"},{"internalType":"bool","name":"requiresDeposit","type":"bool"}],"internalType":"struct LibSwap.SwapData[]","name":"swapData","type":"tuple[]"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"string","name":"bridge","type":"string"},{"internalType":"address","name":"sendingAssetId","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"destinationChainId","type":"uint256"},{"internalType":"bool","name":"hasSourceSwaps","type":"bool"},{"internalType":"bool","name":"hasDestinationCall","type":"bool"}],"name":"validateCalldata","outputs":[{"internalType":"bool","name":"isValid","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"bytes","name":"callTo","type":"bytes"},{"internalType":"bytes","name":"dstCalldata","type":"bytes"}],"name":"validateDestinationCalldata","outputs":[{"internalType":"bool","name":"isValid","type":"bool"}],"stateMutability":"pure","type":"function"}]
Contract Creation Code
608060405234801561001057600080fd5b5061238e806100206000396000f3fe608060405234801561001057600080fd5b506004361061007d5760003560e01c8063c318eeda1161005b578063c318eeda146100ec578063d53482cf14610147578063ee0aa3201461016a578063f58ae2ce1461019057600080fd5b8063070e81f114610082578063103c5200146100ab5780637f99d7af146100cc575b600080fd5b610095610090366004610fa0565b6101a3565b6040516100a2919061113d565b60405180910390f35b6100be6100b9366004610fa0565b6101b6565b6040516100a2929190611245565b6100df6100da366004610fa0565b610231565b6040516100a29190611273565b6100ff6100fa366004610fa0565b61028d565b6040805173ffffffffffffffffffffffffffffffffffffffff96871681526020810195909552928516928401929092529092166060820152608081019190915260a0016100a2565b61015a6101553660046112d4565b610405565b60405190151581526020016100a2565b61017d610178366004610fa0565b610696565b6040516100a297969594939291906113a3565b61015a61019e366004611401565b610751565b60606101af8383610c5c565b9392505050565b604080516101408101825260008082526060602083018190529282018390528282018190526080820181905260a0820181905260c0820181905260e082018190526101008201819052610120820152906102108484610d2e565b91508161010001511561022a576102278484610c5c565b90505b9250929050565b604080516101408101825260008082526060602083018190529282018390529181018290526080810182905260a0810182905260c0810182905260e0810182905261010081018290526101208101919091526101af8383610d2e565b60008060008060006060600088888080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509394507fd6a4bc50000000000000000000000000000000000000000000000000000000009361030293506004925090508b8d61149b565b61030b916114c5565b7fffffffff00000000000000000000000000000000000000000000000000000000160361034f5761033f886004818c61149b565b81019061034c91906116bb565b90505b61036960048083516103619190611727565b839190610e44565b80602001905181019061037c9190611900565b8051929a509097509550859350600092501515905061039d5761039d6119ae565b6020026020010151604001519650816000815181106103be576103be6119ae565b602002602001015160800151955081600183516103db9190611727565b815181106103eb576103eb6119ae565b602002602001015160600151935050509295509295909350565b604080516101408101825260008082526060602083018190529282018390529181018290526080810182905260a0810182905260c0810182905260e08101829052610100810182905261012081018290526104608c8c610696565b1515610120880152151561010087015260e086015260c085015273ffffffffffffffffffffffffffffffffffffffff90811660a0850152166080830152602080830191909152604080516000815291820180825282519020916104c7918d918d91016119dd565b60405160208183030381529060405280519060200120148061053a575089896040516020016104f79291906119dd565b60405160208183030381529060405280519060200120816020015160405160200161052291906119ed565b60405160208183030381529060405280519060200120145b8015610594575073ffffffffffffffffffffffffffffffffffffffff808916148061059457508773ffffffffffffffffffffffffffffffffffffffff16816080015173ffffffffffffffffffffffffffffffffffffffff16145b80156105ee575073ffffffffffffffffffffffffffffffffffffffff80881614806105ee57508673ffffffffffffffffffffffffffffffffffffffff168160a0015173ffffffffffffffffffffffffffffffffffffffff16145b801561062657507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8614806106265750858160c00151145b801561065e57507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff85148061065e5750848160e00151145b801561067257508315158161010001511515145b801561068657508215158161012001511515145b9c9b505050505050505050505050565b606060008060008060008060006106ad8a8a610d2e565b9050806101000151156107105760006106c68b8b610c5c565b9050806000815181106106db576106db6119ae565b6020026020010151604001519750806000815181106106fc576106fc6119ae565b60200260200101516080015195505061071f565b806080015196508060c0015194505b602081015160a082015160e083015161010084015161012090940151929d999c50909a50959850949690955092505050565b60008087878080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509394507fd6a4bc5000000000000000000000000000000000000000000000000000000000936107bd93506004925090508a8c61149b565b6107c6916114c5565b7fffffffff00000000000000000000000000000000000000000000000000000000160361080a576107fa876004818b61149b565b81019061080791906116bb565b90505b6000818060200190518101906108209190611a09565b90507f72366cd3000000000000000000000000000000000000000000000000000000007fffffffff00000000000000000000000000000000000000000000000000000000821601610912576000610887600480855161087f9190611727565b859190610e44565b80602001905181019061089a9190611be4565b91505080600001518051906020012086866040516108b99291906119dd565b60405180910390201480156109085750602081015173ffffffffffffffffffffffffffffffffffffffff166108f0888a018a611c48565b73ffffffffffffffffffffffffffffffffffffffff16145b9350505050610c52565b7f7c0ce6e9000000000000000000000000000000000000000000000000000000007fffffffff000000000000000000000000000000000000000000000000000000008216016109a257600061096f600480855161087f9190611727565b8060200190518101906109829190611c65565b9250505080600001518051906020012086866040516108b99291906119dd565b7f41e15319000000000000000000000000000000000000000000000000000000007fffffffff00000000000000000000000000000000000000000000000000000000821601610a705760006109ff600480855161087f9190611727565b806020019051810190610a129190611da0565b9150508060e00151805190602001208686604051610a319291906119dd565b604051809103902014801561090857508060c00151805190602001208888604051610a5d9291906119dd565b6040518091039020149350505050610c52565b7f12e879e7000000000000000000000000000000000000000000000000000000007fffffffff00000000000000000000000000000000000000000000000000000000821601610b00576000610acd600480855161087f9190611727565b806020019051810190610ae09190611dfa565b925050508060e00151805190602001208686604051610a319291906119dd565b7ffaf6a213000000000000000000000000000000000000000000000000000000007fffffffff00000000000000000000000000000000000000000000000000000000821601610bbb576000610b5d600480855161087f9190611727565b806020019051810190610b709190611f4b565b9150508060600151805190602001208686604051610b8f9291906119dd565b604051809103902014801561090857508060400151805190602001208888604051610a5d9291906119dd565b7f4f93ad26000000000000000000000000000000000000000000000000000000007fffffffff00000000000000000000000000000000000000000000000000000000821601610c4b576000610c18600480855161087f9190611727565b806020019051810190610c2b9190611fa5565b925050508060600151805190602001208686604051610b8f9291906119dd565b6000925050505b9695505050505050565b60607fd6a4bc5000000000000000000000000000000000000000000000000000000000610c8d60046000858761149b565b610c96916114c5565b7fffffffff000000000000000000000000000000000000000000000000000000001603610d0a576000610ccc836004818761149b565b810190610cd991906116bb565b9050610ced60048083516103619190611727565b806020019051810190610d009190612023565b9250610d28915050565b610d17826004818661149b565b810190610d249190612158565b9150505b92915050565b604080516101408101825260008082526060602083018190529282018390529181018290526080810182905260a0810182905260c0810182905260e0810182905261010081018290526101208101919091527fd6a4bc5000000000000000000000000000000000000000000000000000000000610daf60046000858761149b565b610db8916114c5565b7fffffffff000000000000000000000000000000000000000000000000000000001603610e2a576000610dee836004818761149b565b810190610dfb91906116bb565b9050610e0f60048083516103619190611727565b806020019051810190610e2291906122db565b915050610d28565b610e37826004818661149b565b8101906101af9190612310565b606081610e5281601f612345565b1015610e8a576040517f47aaf07a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b610e948284612345565b84511015610ece576040517f3b99b53d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b606082158015610eed5760405191506000825260208201604052610f55565b6040519150601f8416801560200281840101858101878315602002848b0101015b81831015610f26578051835260209283019201610f0e565b5050858452601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016604052505b50949350505050565b60008083601f840112610f7057600080fd5b50813567ffffffffffffffff811115610f8857600080fd5b60208301915083602082850101111561022a57600080fd5b60008060208385031215610fb357600080fd5b823567ffffffffffffffff811115610fca57600080fd5b610fd685828601610f5e565b90969095509350505050565b60005b83811015610ffd578181015183820152602001610fe5565b50506000910152565b6000815180845261101e816020860160208601610fe2565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b600082825180855260208086019550808260051b84010181860160005b84811015611130577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08684030189528151805173ffffffffffffffffffffffffffffffffffffffff908116855285820151811686860152604080830151821690860152606080830151909116908501526080808201519085015260a08082015160e0828701819052919061110383880182611006565b9250505060c080830151925061111c8187018415159052565b50998501999350509083019060010161106d565b5090979650505050505050565b6020815260006101af6020830184611050565b600061014082518452602083015181602086015261117082860182611006565b9150506040830151848203604086015261118a8282611006565b91505060608301516111b4606086018273ffffffffffffffffffffffffffffffffffffffff169052565b5060808301516111dc608086018273ffffffffffffffffffffffffffffffffffffffff169052565b5060a083015161120460a086018273ffffffffffffffffffffffffffffffffffffffff169052565b5060c083015160c085015260e083015160e08501526101008084015161122d8287018215159052565b50506101209283015115159390920192909252919050565b6040815260006112586040830185611150565b828103602084015261126a8185611050565b95945050505050565b6020815260006101af6020830184611150565b73ffffffffffffffffffffffffffffffffffffffff811681146112a857600080fd5b50565b80356112b681611286565b919050565b80151581146112a857600080fd5b80356112b6816112bb565b6000806000806000806000806000806101008b8d0312156112f457600080fd5b8a3567ffffffffffffffff8082111561130c57600080fd5b6113188e838f01610f5e565b909c509a5060208d013591508082111561133157600080fd5b5061133e8d828e01610f5e565b90995097505060408b013561135281611286565b955060608b013561136281611286565b945060808b0135935060a08b0135925060c08b0135611380816112bb565b915060e08b0135611390816112bb565b809150509295989b9194979a5092959850565b60e0815260006113b660e083018a611006565b73ffffffffffffffffffffffffffffffffffffffff988916602084015296909716604082015260608101949094526080840192909252151560a0830152151560c09091015292915050565b6000806000806000806060878903121561141a57600080fd5b863567ffffffffffffffff8082111561143257600080fd5b61143e8a838b01610f5e565b9098509650602089013591508082111561145757600080fd5b6114638a838b01610f5e565b9096509450604089013591508082111561147c57600080fd5b5061148989828a01610f5e565b979a9699509497509295939492505050565b600080858511156114ab57600080fd5b838611156114b857600080fd5b5050820193919092039150565b7fffffffff0000000000000000000000000000000000000000000000000000000081358181169160048510156115055780818660040360031b1b83161692505b505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b60405160e0810167ffffffffffffffff8111828210171561155f5761155f61150d565b60405290565b604051610140810167ffffffffffffffff8111828210171561155f5761155f61150d565b604051610100810167ffffffffffffffff8111828210171561155f5761155f61150d565b60405160c0810167ffffffffffffffff8111828210171561155f5761155f61150d565b604051601f82017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016810167ffffffffffffffff811182821017156116175761161761150d565b604052919050565b600067ffffffffffffffff8211156116395761163961150d565b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01660200190565b600082601f83011261167657600080fd5b81356116896116848261161f565b6115d0565b81815284602083860101111561169e57600080fd5b816020850160208301376000918101602001919091529392505050565b6000602082840312156116cd57600080fd5b813567ffffffffffffffff8111156116e457600080fd5b6116f084828501611665565b949350505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b81810381811115610d2857610d286116f8565b600082601f83011261174b57600080fd5b81516117596116848261161f565b81815284602083860101111561176e57600080fd5b6116f0826020830160208701610fe2565b80516112b681611286565b600067ffffffffffffffff8211156117a4576117a461150d565b5060051b60200190565b80516112b6816112bb565b600082601f8301126117ca57600080fd5b815160206117da6116848361178a565b82815260059290921b840181019181810190868411156117f957600080fd5b8286015b848110156118f557805167ffffffffffffffff8082111561181e5760008081fd5b818901915060e0807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0848d030112156118575760008081fd5b61185f61153c565b61186a88850161177f565b8152604061187981860161177f565b89830152606061188a81870161177f565b828401526080915061189d82870161177f565b818401525060a0808601518284015260c0915081860151858111156118c25760008081fd5b6118d08f8c838a010161173a565b8285015250506118e18386016117ae565b9082015286525050509183019183016117fd565b509695505050505050565b60008060008060008060c0878903121561191957600080fd5b86519550602087015167ffffffffffffffff8082111561193857600080fd5b6119448a838b0161173a565b9650604089015191508082111561195a57600080fd5b6119668a838b0161173a565b95506060890151915061197882611286565b608089015160a08a015192955093508082111561199457600080fd5b506119a189828a016117b9565b9150509295509295509295565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b8183823760009101908152919050565b600082516119ff818460208701610fe2565b9190910192915050565b600060208284031215611a1b57600080fd5b81517fffffffff00000000000000000000000000000000000000000000000000000000811681146101af57600080fd5b60006101408284031215611a5e57600080fd5b611a66611565565b905081518152602082015167ffffffffffffffff80821115611a8757600080fd5b611a938583860161173a565b60208401526040840151915080821115611aac57600080fd5b50611ab98482850161173a565b604083015250611acb6060830161177f565b6060820152611adc6080830161177f565b6080820152611aed60a0830161177f565b60a082015260c082015160c082015260e082015160e0820152610100611b148184016117ae565b90820152610120611b268382016117ae565b9082015292915050565b805163ffffffff811681146112b657600080fd5b600060e08284031215611b5657600080fd5b611b5e61153c565b9050815167ffffffffffffffff811115611b7757600080fd5b611b838482850161173a565b825250611b926020830161177f565b60208201526040820151604082015260608201516060820152611bb76080830161177f565b6080820152611bc860a08301611b30565b60a0820152611bd960c083016117ae565b60c082015292915050565b60008060408385031215611bf757600080fd5b825167ffffffffffffffff80821115611c0f57600080fd5b611c1b86838701611a4b565b93506020850151915080821115611c3157600080fd5b50611c3e85828601611b44565b9150509250929050565b600060208284031215611c5a57600080fd5b81356101af81611286565b600080600060608486031215611c7a57600080fd5b835167ffffffffffffffff80821115611c9257600080fd5b611c9e87838801611a4b565b94506020860151915080821115611cb457600080fd5b611cc0878388016117b9565b93506040860151915080821115611cd657600080fd5b50611ce386828701611b44565b9150509250925092565b60006101008284031215611d0057600080fd5b611d08611589565b90508151815260208201516020820152604082015160408201526060820151606082015260808201516080820152611d4260a0830161177f565b60a082015260c082015167ffffffffffffffff80821115611d6257600080fd5b611d6e8583860161173a565b60c084015260e0840151915080821115611d8757600080fd5b50611d948482850161173a565b60e08301525092915050565b60008060408385031215611db357600080fd5b825167ffffffffffffffff80821115611dcb57600080fd5b611dd786838701611a4b565b93506020850151915080821115611ded57600080fd5b50611c3e85828601611ced565b600080600060608486031215611e0f57600080fd5b835167ffffffffffffffff80821115611e2757600080fd5b611e3387838801611a4b565b94506020860151915080821115611e4957600080fd5b611e55878388016117b9565b93506040860151915080821115611e6b57600080fd5b50611ce386828701611ced565b805167ffffffffffffffff811681146112b657600080fd5b8051600781106112b657600080fd5b600060c08284031215611eb157600080fd5b611eb96115ad565b9050611ec482611b30565b8152611ed260208301611e78565b6020820152604082015167ffffffffffffffff80821115611ef257600080fd5b611efe8583860161173a565b60408401526060840151915080821115611f1757600080fd5b50611f248482850161173a565b60608301525060808201516080820152611f4060a08301611e90565b60a082015292915050565b60008060408385031215611f5e57600080fd5b825167ffffffffffffffff80821115611f7657600080fd5b611f8286838701611a4b565b93506020850151915080821115611f9857600080fd5b50611c3e85828601611e9f565b600080600060608486031215611fba57600080fd5b835167ffffffffffffffff80821115611fd257600080fd5b611fde87838801611a4b565b94506020860151915080821115611ff457600080fd5b612000878388016117b9565b9350604086015191508082111561201657600080fd5b50611ce386828701611e9f565b6000806040838503121561203657600080fd5b825167ffffffffffffffff8082111561204e57600080fd5b61205a86838701611a4b565b9350602085015191508082111561207057600080fd5b50611c3e858286016117b9565b6000610140828403121561209057600080fd5b612098611565565b905081358152602082013567ffffffffffffffff808211156120b957600080fd5b6120c585838601611665565b602084015260408401359150808211156120de57600080fd5b506120eb84828501611665565b6040830152506120fd606083016112ab565b606082015261210e608083016112ab565b608082015261211f60a083016112ab565b60a082015260c082013560c082015260e082013560e08201526101006121468184016112c9565b90820152610120611b268382016112c9565b6000806040838503121561216b57600080fd5b823567ffffffffffffffff8082111561218357600080fd5b61218f8683870161207d565b93506020915081850135818111156121a657600080fd5b8501601f810187136121b757600080fd5b80356121c56116848261178a565b81815260059190911b820184019084810190898311156121e457600080fd5b8584015b838110156122ca578035868111156121ff57600080fd5b850160e0818d037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe001121561223357600080fd5b61223b61153c565b6122468983016112ab565b8152612254604083016112ab565b89820152612264606083016112ab565b6040820152612275608083016112ab565b606082015260a0820135608082015260c080830135898111156122985760008081fd5b6122a68f8c83870101611665565b60a0840152506122b860e084016112c9565b908201528452509186019186016121e8565b508096505050505050509250929050565b6000602082840312156122ed57600080fd5b815167ffffffffffffffff81111561230457600080fd5b6116f084828501611a4b565b60006020828403121561232257600080fd5b813567ffffffffffffffff81111561233957600080fd5b6116f08482850161207d565b80820180821115610d2857610d286116f856fea2646970667358221220521a20c9b213904dff111937bed46923bf850bcb4d2dd34162b04b545111994664736f6c63430008110033
Deployed Bytecode
0x608060405234801561001057600080fd5b506004361061007d5760003560e01c8063c318eeda1161005b578063c318eeda146100ec578063d53482cf14610147578063ee0aa3201461016a578063f58ae2ce1461019057600080fd5b8063070e81f114610082578063103c5200146100ab5780637f99d7af146100cc575b600080fd5b610095610090366004610fa0565b6101a3565b6040516100a2919061113d565b60405180910390f35b6100be6100b9366004610fa0565b6101b6565b6040516100a2929190611245565b6100df6100da366004610fa0565b610231565b6040516100a29190611273565b6100ff6100fa366004610fa0565b61028d565b6040805173ffffffffffffffffffffffffffffffffffffffff96871681526020810195909552928516928401929092529092166060820152608081019190915260a0016100a2565b61015a6101553660046112d4565b610405565b60405190151581526020016100a2565b61017d610178366004610fa0565b610696565b6040516100a297969594939291906113a3565b61015a61019e366004611401565b610751565b60606101af8383610c5c565b9392505050565b604080516101408101825260008082526060602083018190529282018390528282018190526080820181905260a0820181905260c0820181905260e082018190526101008201819052610120820152906102108484610d2e565b91508161010001511561022a576102278484610c5c565b90505b9250929050565b604080516101408101825260008082526060602083018190529282018390529181018290526080810182905260a0810182905260c0810182905260e0810182905261010081018290526101208101919091526101af8383610d2e565b60008060008060006060600088888080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509394507fd6a4bc50000000000000000000000000000000000000000000000000000000009361030293506004925090508b8d61149b565b61030b916114c5565b7fffffffff00000000000000000000000000000000000000000000000000000000160361034f5761033f886004818c61149b565b81019061034c91906116bb565b90505b61036960048083516103619190611727565b839190610e44565b80602001905181019061037c9190611900565b8051929a509097509550859350600092501515905061039d5761039d6119ae565b6020026020010151604001519650816000815181106103be576103be6119ae565b602002602001015160800151955081600183516103db9190611727565b815181106103eb576103eb6119ae565b602002602001015160600151935050509295509295909350565b604080516101408101825260008082526060602083018190529282018390529181018290526080810182905260a0810182905260c0810182905260e08101829052610100810182905261012081018290526104608c8c610696565b1515610120880152151561010087015260e086015260c085015273ffffffffffffffffffffffffffffffffffffffff90811660a0850152166080830152602080830191909152604080516000815291820180825282519020916104c7918d918d91016119dd565b60405160208183030381529060405280519060200120148061053a575089896040516020016104f79291906119dd565b60405160208183030381529060405280519060200120816020015160405160200161052291906119ed565b60405160208183030381529060405280519060200120145b8015610594575073ffffffffffffffffffffffffffffffffffffffff808916148061059457508773ffffffffffffffffffffffffffffffffffffffff16816080015173ffffffffffffffffffffffffffffffffffffffff16145b80156105ee575073ffffffffffffffffffffffffffffffffffffffff80881614806105ee57508673ffffffffffffffffffffffffffffffffffffffff168160a0015173ffffffffffffffffffffffffffffffffffffffff16145b801561062657507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8614806106265750858160c00151145b801561065e57507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff85148061065e5750848160e00151145b801561067257508315158161010001511515145b801561068657508215158161012001511515145b9c9b505050505050505050505050565b606060008060008060008060006106ad8a8a610d2e565b9050806101000151156107105760006106c68b8b610c5c565b9050806000815181106106db576106db6119ae565b6020026020010151604001519750806000815181106106fc576106fc6119ae565b60200260200101516080015195505061071f565b806080015196508060c0015194505b602081015160a082015160e083015161010084015161012090940151929d999c50909a50959850949690955092505050565b60008087878080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509394507fd6a4bc5000000000000000000000000000000000000000000000000000000000936107bd93506004925090508a8c61149b565b6107c6916114c5565b7fffffffff00000000000000000000000000000000000000000000000000000000160361080a576107fa876004818b61149b565b81019061080791906116bb565b90505b6000818060200190518101906108209190611a09565b90507f72366cd3000000000000000000000000000000000000000000000000000000007fffffffff00000000000000000000000000000000000000000000000000000000821601610912576000610887600480855161087f9190611727565b859190610e44565b80602001905181019061089a9190611be4565b91505080600001518051906020012086866040516108b99291906119dd565b60405180910390201480156109085750602081015173ffffffffffffffffffffffffffffffffffffffff166108f0888a018a611c48565b73ffffffffffffffffffffffffffffffffffffffff16145b9350505050610c52565b7f7c0ce6e9000000000000000000000000000000000000000000000000000000007fffffffff000000000000000000000000000000000000000000000000000000008216016109a257600061096f600480855161087f9190611727565b8060200190518101906109829190611c65565b9250505080600001518051906020012086866040516108b99291906119dd565b7f41e15319000000000000000000000000000000000000000000000000000000007fffffffff00000000000000000000000000000000000000000000000000000000821601610a705760006109ff600480855161087f9190611727565b806020019051810190610a129190611da0565b9150508060e00151805190602001208686604051610a319291906119dd565b604051809103902014801561090857508060c00151805190602001208888604051610a5d9291906119dd565b6040518091039020149350505050610c52565b7f12e879e7000000000000000000000000000000000000000000000000000000007fffffffff00000000000000000000000000000000000000000000000000000000821601610b00576000610acd600480855161087f9190611727565b806020019051810190610ae09190611dfa565b925050508060e00151805190602001208686604051610a319291906119dd565b7ffaf6a213000000000000000000000000000000000000000000000000000000007fffffffff00000000000000000000000000000000000000000000000000000000821601610bbb576000610b5d600480855161087f9190611727565b806020019051810190610b709190611f4b565b9150508060600151805190602001208686604051610b8f9291906119dd565b604051809103902014801561090857508060400151805190602001208888604051610a5d9291906119dd565b7f4f93ad26000000000000000000000000000000000000000000000000000000007fffffffff00000000000000000000000000000000000000000000000000000000821601610c4b576000610c18600480855161087f9190611727565b806020019051810190610c2b9190611fa5565b925050508060600151805190602001208686604051610b8f9291906119dd565b6000925050505b9695505050505050565b60607fd6a4bc5000000000000000000000000000000000000000000000000000000000610c8d60046000858761149b565b610c96916114c5565b7fffffffff000000000000000000000000000000000000000000000000000000001603610d0a576000610ccc836004818761149b565b810190610cd991906116bb565b9050610ced60048083516103619190611727565b806020019051810190610d009190612023565b9250610d28915050565b610d17826004818661149b565b810190610d249190612158565b9150505b92915050565b604080516101408101825260008082526060602083018190529282018390529181018290526080810182905260a0810182905260c0810182905260e0810182905261010081018290526101208101919091527fd6a4bc5000000000000000000000000000000000000000000000000000000000610daf60046000858761149b565b610db8916114c5565b7fffffffff000000000000000000000000000000000000000000000000000000001603610e2a576000610dee836004818761149b565b810190610dfb91906116bb565b9050610e0f60048083516103619190611727565b806020019051810190610e2291906122db565b915050610d28565b610e37826004818661149b565b8101906101af9190612310565b606081610e5281601f612345565b1015610e8a576040517f47aaf07a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b610e948284612345565b84511015610ece576040517f3b99b53d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b606082158015610eed5760405191506000825260208201604052610f55565b6040519150601f8416801560200281840101858101878315602002848b0101015b81831015610f26578051835260209283019201610f0e565b5050858452601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016604052505b50949350505050565b60008083601f840112610f7057600080fd5b50813567ffffffffffffffff811115610f8857600080fd5b60208301915083602082850101111561022a57600080fd5b60008060208385031215610fb357600080fd5b823567ffffffffffffffff811115610fca57600080fd5b610fd685828601610f5e565b90969095509350505050565b60005b83811015610ffd578181015183820152602001610fe5565b50506000910152565b6000815180845261101e816020860160208601610fe2565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b600082825180855260208086019550808260051b84010181860160005b84811015611130577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08684030189528151805173ffffffffffffffffffffffffffffffffffffffff908116855285820151811686860152604080830151821690860152606080830151909116908501526080808201519085015260a08082015160e0828701819052919061110383880182611006565b9250505060c080830151925061111c8187018415159052565b50998501999350509083019060010161106d565b5090979650505050505050565b6020815260006101af6020830184611050565b600061014082518452602083015181602086015261117082860182611006565b9150506040830151848203604086015261118a8282611006565b91505060608301516111b4606086018273ffffffffffffffffffffffffffffffffffffffff169052565b5060808301516111dc608086018273ffffffffffffffffffffffffffffffffffffffff169052565b5060a083015161120460a086018273ffffffffffffffffffffffffffffffffffffffff169052565b5060c083015160c085015260e083015160e08501526101008084015161122d8287018215159052565b50506101209283015115159390920192909252919050565b6040815260006112586040830185611150565b828103602084015261126a8185611050565b95945050505050565b6020815260006101af6020830184611150565b73ffffffffffffffffffffffffffffffffffffffff811681146112a857600080fd5b50565b80356112b681611286565b919050565b80151581146112a857600080fd5b80356112b6816112bb565b6000806000806000806000806000806101008b8d0312156112f457600080fd5b8a3567ffffffffffffffff8082111561130c57600080fd5b6113188e838f01610f5e565b909c509a5060208d013591508082111561133157600080fd5b5061133e8d828e01610f5e565b90995097505060408b013561135281611286565b955060608b013561136281611286565b945060808b0135935060a08b0135925060c08b0135611380816112bb565b915060e08b0135611390816112bb565b809150509295989b9194979a5092959850565b60e0815260006113b660e083018a611006565b73ffffffffffffffffffffffffffffffffffffffff988916602084015296909716604082015260608101949094526080840192909252151560a0830152151560c09091015292915050565b6000806000806000806060878903121561141a57600080fd5b863567ffffffffffffffff8082111561143257600080fd5b61143e8a838b01610f5e565b9098509650602089013591508082111561145757600080fd5b6114638a838b01610f5e565b9096509450604089013591508082111561147c57600080fd5b5061148989828a01610f5e565b979a9699509497509295939492505050565b600080858511156114ab57600080fd5b838611156114b857600080fd5b5050820193919092039150565b7fffffffff0000000000000000000000000000000000000000000000000000000081358181169160048510156115055780818660040360031b1b83161692505b505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b60405160e0810167ffffffffffffffff8111828210171561155f5761155f61150d565b60405290565b604051610140810167ffffffffffffffff8111828210171561155f5761155f61150d565b604051610100810167ffffffffffffffff8111828210171561155f5761155f61150d565b60405160c0810167ffffffffffffffff8111828210171561155f5761155f61150d565b604051601f82017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016810167ffffffffffffffff811182821017156116175761161761150d565b604052919050565b600067ffffffffffffffff8211156116395761163961150d565b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01660200190565b600082601f83011261167657600080fd5b81356116896116848261161f565b6115d0565b81815284602083860101111561169e57600080fd5b816020850160208301376000918101602001919091529392505050565b6000602082840312156116cd57600080fd5b813567ffffffffffffffff8111156116e457600080fd5b6116f084828501611665565b949350505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b81810381811115610d2857610d286116f8565b600082601f83011261174b57600080fd5b81516117596116848261161f565b81815284602083860101111561176e57600080fd5b6116f0826020830160208701610fe2565b80516112b681611286565b600067ffffffffffffffff8211156117a4576117a461150d565b5060051b60200190565b80516112b6816112bb565b600082601f8301126117ca57600080fd5b815160206117da6116848361178a565b82815260059290921b840181019181810190868411156117f957600080fd5b8286015b848110156118f557805167ffffffffffffffff8082111561181e5760008081fd5b818901915060e0807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0848d030112156118575760008081fd5b61185f61153c565b61186a88850161177f565b8152604061187981860161177f565b89830152606061188a81870161177f565b828401526080915061189d82870161177f565b818401525060a0808601518284015260c0915081860151858111156118c25760008081fd5b6118d08f8c838a010161173a565b8285015250506118e18386016117ae565b9082015286525050509183019183016117fd565b509695505050505050565b60008060008060008060c0878903121561191957600080fd5b86519550602087015167ffffffffffffffff8082111561193857600080fd5b6119448a838b0161173a565b9650604089015191508082111561195a57600080fd5b6119668a838b0161173a565b95506060890151915061197882611286565b608089015160a08a015192955093508082111561199457600080fd5b506119a189828a016117b9565b9150509295509295509295565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b8183823760009101908152919050565b600082516119ff818460208701610fe2565b9190910192915050565b600060208284031215611a1b57600080fd5b81517fffffffff00000000000000000000000000000000000000000000000000000000811681146101af57600080fd5b60006101408284031215611a5e57600080fd5b611a66611565565b905081518152602082015167ffffffffffffffff80821115611a8757600080fd5b611a938583860161173a565b60208401526040840151915080821115611aac57600080fd5b50611ab98482850161173a565b604083015250611acb6060830161177f565b6060820152611adc6080830161177f565b6080820152611aed60a0830161177f565b60a082015260c082015160c082015260e082015160e0820152610100611b148184016117ae565b90820152610120611b268382016117ae565b9082015292915050565b805163ffffffff811681146112b657600080fd5b600060e08284031215611b5657600080fd5b611b5e61153c565b9050815167ffffffffffffffff811115611b7757600080fd5b611b838482850161173a565b825250611b926020830161177f565b60208201526040820151604082015260608201516060820152611bb76080830161177f565b6080820152611bc860a08301611b30565b60a0820152611bd960c083016117ae565b60c082015292915050565b60008060408385031215611bf757600080fd5b825167ffffffffffffffff80821115611c0f57600080fd5b611c1b86838701611a4b565b93506020850151915080821115611c3157600080fd5b50611c3e85828601611b44565b9150509250929050565b600060208284031215611c5a57600080fd5b81356101af81611286565b600080600060608486031215611c7a57600080fd5b835167ffffffffffffffff80821115611c9257600080fd5b611c9e87838801611a4b565b94506020860151915080821115611cb457600080fd5b611cc0878388016117b9565b93506040860151915080821115611cd657600080fd5b50611ce386828701611b44565b9150509250925092565b60006101008284031215611d0057600080fd5b611d08611589565b90508151815260208201516020820152604082015160408201526060820151606082015260808201516080820152611d4260a0830161177f565b60a082015260c082015167ffffffffffffffff80821115611d6257600080fd5b611d6e8583860161173a565b60c084015260e0840151915080821115611d8757600080fd5b50611d948482850161173a565b60e08301525092915050565b60008060408385031215611db357600080fd5b825167ffffffffffffffff80821115611dcb57600080fd5b611dd786838701611a4b565b93506020850151915080821115611ded57600080fd5b50611c3e85828601611ced565b600080600060608486031215611e0f57600080fd5b835167ffffffffffffffff80821115611e2757600080fd5b611e3387838801611a4b565b94506020860151915080821115611e4957600080fd5b611e55878388016117b9565b93506040860151915080821115611e6b57600080fd5b50611ce386828701611ced565b805167ffffffffffffffff811681146112b657600080fd5b8051600781106112b657600080fd5b600060c08284031215611eb157600080fd5b611eb96115ad565b9050611ec482611b30565b8152611ed260208301611e78565b6020820152604082015167ffffffffffffffff80821115611ef257600080fd5b611efe8583860161173a565b60408401526060840151915080821115611f1757600080fd5b50611f248482850161173a565b60608301525060808201516080820152611f4060a08301611e90565b60a082015292915050565b60008060408385031215611f5e57600080fd5b825167ffffffffffffffff80821115611f7657600080fd5b611f8286838701611a4b565b93506020850151915080821115611f9857600080fd5b50611c3e85828601611e9f565b600080600060608486031215611fba57600080fd5b835167ffffffffffffffff80821115611fd257600080fd5b611fde87838801611a4b565b94506020860151915080821115611ff457600080fd5b612000878388016117b9565b9350604086015191508082111561201657600080fd5b50611ce386828701611e9f565b6000806040838503121561203657600080fd5b825167ffffffffffffffff8082111561204e57600080fd5b61205a86838701611a4b565b9350602085015191508082111561207057600080fd5b50611c3e858286016117b9565b6000610140828403121561209057600080fd5b612098611565565b905081358152602082013567ffffffffffffffff808211156120b957600080fd5b6120c585838601611665565b602084015260408401359150808211156120de57600080fd5b506120eb84828501611665565b6040830152506120fd606083016112ab565b606082015261210e608083016112ab565b608082015261211f60a083016112ab565b60a082015260c082013560c082015260e082013560e08201526101006121468184016112c9565b90820152610120611b268382016112c9565b6000806040838503121561216b57600080fd5b823567ffffffffffffffff8082111561218357600080fd5b61218f8683870161207d565b93506020915081850135818111156121a657600080fd5b8501601f810187136121b757600080fd5b80356121c56116848261178a565b81815260059190911b820184019084810190898311156121e457600080fd5b8584015b838110156122ca578035868111156121ff57600080fd5b850160e0818d037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe001121561223357600080fd5b61223b61153c565b6122468983016112ab565b8152612254604083016112ab565b89820152612264606083016112ab565b6040820152612275608083016112ab565b606082015260a0820135608082015260c080830135898111156122985760008081fd5b6122a68f8c83870101611665565b60a0840152506122b860e084016112c9565b908201528452509186019186016121e8565b508096505050505050509250929050565b6000602082840312156122ed57600080fd5b815167ffffffffffffffff81111561230457600080fd5b6116f084828501611a4b565b60006020828403121561232257600080fd5b813567ffffffffffffffff81111561233957600080fd5b6116f08482850161207d565b80820180821115610d2857610d286116f856fea2646970667358221220521a20c9b213904dff111937bed46923bf850bcb4d2dd34162b04b545111994664736f6c63430008110033
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 31 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.