ETH Price: $1,944.13 (-1.51%)

Transaction Decoder

Block:
24509996 at Feb-22-2026 04:24:11 AM +UTC
Transaction Fee:
0.000019956360831896 ETH $0.04
Gas Used:
184,924 Gas / 0.107916554 Gwei

Emitted Events:

21 FeeCollector.FeesCollected( _token=0x00000000...000000000, _integrator=0xA4d9D706...5BCD41984, _integratorFee=45200409942936, _lifiFee=2378968944365 )
22 LiFiDiamond.0x7bfdfdb5e3a3776976e53cb0607060f54c5312701c8cba1155cc4d5394440b38( 0x7bfdfdb5e3a3776976e53cb0607060f54c5312701c8cba1155cc4d5394440b38, 0236f62ddcefb5dd713c1744df8d27bc02594ad76334097be44d8473c5095ef7, 0000000000000000000000003ef238c36035880efbdfa239d218186b79ad1d6f, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000013e2f6c1156c98, 0000000000000000000000000000000000000000000000000013b7b0d11b4213, 00000000000000000000000000000000000000000000000000000000699a84eb )
23 0xc38e4e6a15593f908255214653d3d947ca1c2338.0x918554b6bd6e2895ce6553de5de0e1a69db5289aa0e4fe193a0dcd1f14347477( 0x918554b6bd6e2895ce6553de5de0e1a69db5289aa0e4fe193a0dcd1f14347477, b1daa2de4c4ed45784110d72d7e8783f9ad60625f9995d13ff2cee9ade09080c )
24 MayanForwarder2.ForwardedEth( mayanProtocol=0xc38e4e6a15593f908255214653d3d947ca1c2338, protocolData=0xB866E1730000000000000000000000006B4D095324CBCC06AB73A2D031598171BF1BD29500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000B7DF9D00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003D79000000000000000000000000000000000000000000000000000000000000596000000000000000000000000000000000000000000000000000000000699A93EBD99F289703A8BC7AF0F657264FCEC305EB06D6671C5D0B37EDFA09DC9253FC830000000000000000000000000000000000000000000000000000000000000001F31E1B125DC6B5BDD16C2EE0E6E18DF1858279EA5FD8E8F3A5584ADB9C19D1C80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000239CD74C7973ACAB85890D4AF361363A694FE1E484C45E55461119D83E0B1E217 )
25 LiFiDiamond.0x815cd8dc72093a13fe3577112c391b6279303956526382ab98772d0239dbf78c( 0x815cd8dc72093a13fe3577112c391b6279303956526382ab98772d0239dbf78c, 0x0236f62ddcefb5dd713c1744df8d27bc02594ad76334097be44d8473c5095ef7, 0x000000000000000000000000000000000000000000000000000416edef1601be, d99f289703a8bc7af0f657264fcec305eb06d6671c5d0b37edfa09dc9253fc83 )
26 LiFiDiamond.0xcba69f43792f9f399347222505213b55af8e0b0b54b893085c2e27ecbe1644f1( 0xcba69f43792f9f399347222505213b55af8e0b0b54b893085c2e27ecbe1644f1, 0000000000000000000000000000000000000000000000000000000000000020, 0236f62ddcefb5dd713c1744df8d27bc02594ad76334097be44d8473c5095ef7, 0000000000000000000000000000000000000000000000000000000000000140, 0000000000000000000000000000000000000000000000000000000000000180, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 00000000000000000000000011f111f111f111f111f111f111f111f111f111f1, 0000000000000000000000000000000000000000000000000013b7afbe74fc00, 000000000000000000000000000000000000000000000000000416edef1601be, 0000000000000000000000000000000000000000000000000000000000000001, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000005, 6d6179616e000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000007, 7068616e746f6d00000000000000000000000000000000000000000000000000 )

Account State Difference:

  Address   Before After State Difference Code
0x3Ef238c3...b79Ad1d6F 177.07817805348700332 Eth177.078225632865890621 Eth0.000047579378887301
0x6B4d0953...1BF1bD295
0.0058755795967414 Eth
Nonce: 0
0.000258053857022203 Eth
Nonce: 1
0.005617525739719197
0.075440589422936212 Eth0.075455198418936212 Eth0.000014608996
0xC38e4e6A...7CA1c2338
(Mayan: Swift)
24.491857707728255332 Eth24.497407697728255332 Eth0.00554999

Execution Trace

ETH 0.0055975739867414 LiFiDiamond.30c48952( )
  • ETH 0.0055975739867414 MayanFacet.swapAndStartBridgeTokensViaMayan( _bridgeData=[{name:transactionId, type:bytes32, order:1, indexed:false, value:0236F62DDCEFB5DD713C1744DF8D27BC02594AD76334097BE44D8473C5095EF7, valueString:0236F62DDCEFB5DD713C1744DF8D27BC02594AD76334097BE44D8473C5095EF7}, {name:bridge, type:string, order:2, indexed:false, value:mayan, valueString:mayan}, {name:integrator, type:string, order:3, indexed:false, value:phantom, valueString:phantom}, {name:referrer, type:address, order:4, indexed:false, value:0x0000000000000000000000000000000000000000, valueString:0x0000000000000000000000000000000000000000}, {name:sendingAssetId, type:address, order:5, indexed:false, value:0x0000000000000000000000000000000000000000, valueString:0x0000000000000000000000000000000000000000}, {name:receiver, type:address, order:6, indexed:false, value:0x11f111f111f111F111f111f111F111f111f111F1, valueString:0x11f111f111f111F111f111f111F111f111f111F1}, {name:minAmount, type:uint256, order:7, indexed:false, value:5549994607854099, valueString:5549994607854099}, {name:destinationChainId, type:uint256, order:8, indexed:false, value:1151111081099710, valueString:1151111081099710}, {name:hasSourceSwaps, type:bool, order:9, indexed:false, value:true, valueString:True}, {name:hasDestinationCall, type:bool, order:10, indexed:false, value:false, valueString:False}], _swapData=, _mayanData=[{name:nonEVMReceiver, type:bytes32, order:1, indexed:false, value:D99F289703A8BC7AF0F657264FCEC305EB06D6671C5D0B37EDFA09DC9253FC83, valueString:D99F289703A8BC7AF0F657264FCEC305EB06D6671C5D0B37EDFA09DC9253FC83}, {name:mayanProtocol, type:address, order:2, indexed:false, value:0xC38e4e6A15593f908255214653d3D947CA1c2338, valueString:0xC38e4e6A15593f908255214653d3D947CA1c2338}, {name:protocolData, type:bytes, order:3, indexed:false, value:0xB866E1730000000000000000000000006B4D095324CBCC06AB73A2D031598171BF1BD29500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000B7DF9D00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003D79000000000000000000000000000000000000000000000000000000000000596000000000000000000000000000000000000000000000000000000000699A93EBD99F289703A8BC7AF0F657264FCEC305EB06D6671C5D0B37EDFA09DC9253FC830000000000000000000000000000000000000000000000000000000000000001F31E1B125DC6B5BDD16C2EE0E6E18DF1858279EA5FD8E8F3A5584ADB9C19D1C80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000239CD74C7973ACAB85890D4AF361363A694FE1E484C45E55461119D83E0B1E217, valueString:0xB866E1730000000000000000000000006B4D095324CBCC06AB73A2D031598171BF1BD29500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000B7DF9D00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003D79000000000000000000000000000000000000000000000000000000000000596000000000000000000000000000000000000000000000000000000000699A93EBD99F289703A8BC7AF0F657264FCEC305EB06D6671C5D0B37EDFA09DC9253FC830000000000000000000000000000000000000000000000000000000000000001F31E1B125DC6B5BDD16C2EE0E6E18DF1858279EA5FD8E8F3A5584ADB9C19D1C80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000239CD74C7973ACAB85890D4AF361363A694FE1E484C45E55461119D83E0B1E217}] )
    • ETH 0.0055975739867414 FeeCollector.collectNativeFees( integratorFee=45200409942936, lifiFee=2378968944365, integratorAddress=0xA4d9D7068d84bbDF2E3Caf1bBF2e1135BCD41984 )
      • ETH 0.005549994607854099 LiFiDiamond.CALL( )
      • ETH 0.00554999 MayanForwarder2.forwardEth( mayanProtocol=0xC38e4e6A15593f908255214653d3D947CA1c2338, protocolData=0xB866E1730000000000000000000000006B4D095324CBCC06AB73A2D031598171BF1BD29500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000B7DF9D00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003D79000000000000000000000000000000000000000000000000000000000000596000000000000000000000000000000000000000000000000000000000699A93EBD99F289703A8BC7AF0F657264FCEC305EB06D6671C5D0B37EDFA09DC9253FC830000000000000000000000000000000000000000000000000000000000000001F31E1B125DC6B5BDD16C2EE0E6E18DF1858279EA5FD8E8F3A5584ADB9C19D1C80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000239CD74C7973ACAB85890D4AF361363A694FE1E484C45E55461119D83E0B1E217 )
        • ETH 0.00554999 Mayan: Swift.b866e173( )
          • 0xf93191d350117723dbeda5484a3b0996d285cecf.02fb1eec( )
          • Wormhole.STATICCALL( )
            • 0x3c3d457f1522d3540ab3325aa5f1864e34cba9d0.DELEGATECALL( )
            • Wormhole.STATICCALL( )
              • 0x3c3d457f1522d3540ab3325aa5f1864e34cba9d0.DELEGATECALL( )
              • ETH 0.000000004607854099 0x6b4d095324cbcc06ab73a2d031598171bf1bd295.CALL( )
                File 1 of 5: LiFiDiamond
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                error TokenAddressIsZero();
                error TokenNotSupported();
                error CannotBridgeToSameNetwork();
                error ZeroPostSwapBalance();
                error NoSwapDataProvided();
                error NativeValueWithERC();
                error ContractCallNotAllowed();
                error NullAddrIsNotAValidSpender();
                error NullAddrIsNotAnERC20Token();
                error NoTransferToNullAddress();
                error NativeAssetTransferFailed();
                error InvalidBridgeConfigLength();
                error InvalidAmount();
                error InvalidContract();
                error InvalidConfig();
                error UnsupportedChainId(uint256 chainId);
                error InvalidReceiver();
                error InvalidDestinationChain();
                error InvalidSendingToken();
                error InvalidCaller();
                error AlreadyInitialized();
                error NotInitialized();
                error OnlyContractOwner();
                error CannotAuthoriseSelf();
                error RecoveryAddressCannotBeZero();
                error CannotDepositNativeToken();
                error InvalidCallData();
                error NativeAssetNotSupported();
                error UnAuthorized();
                error NoSwapFromZeroBalance();
                error InvalidFallbackAddress();
                error CumulativeSlippageTooHigh(uint256 minAmount, uint256 receivedAmount);
                error InsufficientBalance(uint256 required, uint256 balance);
                error ZeroAmount();
                error InvalidFee();
                error InformationMismatch();
                error NotAContract();
                error NotEnoughBalance(uint256 requested, uint256 available);
                // 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
                pragma solidity 0.8.17;
                import { LibDiamond } from "./Libraries/LibDiamond.sol";
                import { IDiamondCut } from "./Interfaces/IDiamondCut.sol";
                import { LibUtil } from "./Libraries/LibUtil.sol";
                contract LiFiDiamond {
                    constructor(address _contractOwner, address _diamondCutFacet) payable {
                        LibDiamond.setContractOwner(_contractOwner);
                        // Add the diamondCut external function from the diamondCutFacet
                        IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](1);
                        bytes4[] memory functionSelectors = new bytes4[](1);
                        functionSelectors[0] = IDiamondCut.diamondCut.selector;
                        cut[0] = IDiamondCut.FacetCut({
                            facetAddress: _diamondCutFacet,
                            action: IDiamondCut.FacetCutAction.Add,
                            functionSelectors: functionSelectors
                        });
                        LibDiamond.diamondCut(cut, address(0), "");
                    }
                    // Find facet for function that is called and execute the
                    // function if a facet is found and return any value.
                    // solhint-disable-next-line no-complex-fallback
                    fallback() external payable {
                        LibDiamond.DiamondStorage storage ds;
                        bytes32 position = LibDiamond.DIAMOND_STORAGE_POSITION;
                        // get diamond storage
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            ds.slot := position
                        }
                        // get facet from function selector
                        address facet = ds.selectorToFacetAndPosition[msg.sig].facetAddress;
                        if (facet == address(0)) {
                            revert LibDiamond.FunctionDoesNotExist();
                        }
                        // Execute external function from facet using delegatecall and return any value.
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            // copy function selector and any arguments
                            calldatacopy(0, 0, calldatasize())
                            // execute function call using the facet
                            let result := delegatecall(gas(), facet, 0, calldatasize(), 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())
                            }
                        }
                    }
                    // Able to receive ether
                    // solhint-disable-next-line no-empty-blocks
                    receive() external payable {}
                }
                // 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();
                    error UintOutOfBounds();
                    // -------------------------
                    function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {
                        bytes memory tempBytes;
                        assembly {
                            // Get a location of some free memory and store it in tempBytes as
                            // Solidity does for memory variables.
                            tempBytes := mload(0x40)
                            // Store the length of the first bytes array at the beginning of
                            // the memory for tempBytes.
                            let length := mload(_preBytes)
                            mstore(tempBytes, length)
                            // Maintain a memory counter for the current write location in the
                            // temp bytes array by adding the 32 bytes for the array length to
                            // the starting location.
                            let mc := add(tempBytes, 0x20)
                            // Stop copying when the memory counter reaches the length of the
                            // first bytes array.
                            let end := add(mc, length)
                            for {
                                // Initialize a copy counter to the start of the _preBytes data,
                                // 32 bytes into its memory.
                                let cc := add(_preBytes, 0x20)
                            } lt(mc, end) {
                                // Increase both counters by 32 bytes each iteration.
                                mc := add(mc, 0x20)
                                cc := add(cc, 0x20)
                            } {
                                // Write the _preBytes data into the tempBytes memory 32 bytes
                                // at a time.
                                mstore(mc, mload(cc))
                            }
                            // Add the length of _postBytes to the current length of tempBytes
                            // and store it as the new length in the first 32 bytes of the
                            // tempBytes memory.
                            length := mload(_postBytes)
                            mstore(tempBytes, add(length, mload(tempBytes)))
                            // Move the memory counter back from a multiple of 0x20 to the
                            // actual end of the _preBytes data.
                            mc := end
                            // Stop copying when the memory counter reaches the new combined
                            // length of the arrays.
                            end := add(mc, length)
                            for {
                                let cc := add(_postBytes, 0x20)
                            } lt(mc, end) {
                                mc := add(mc, 0x20)
                                cc := add(cc, 0x20)
                            } {
                                mstore(mc, mload(cc))
                            }
                            // Update the free-memory pointer by padding our last write location
                            // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
                            // next 32 byte block, then round down to the nearest multiple of
                            // 32. If the sum of the length of the two arrays is zero then add
                            // one before rounding down to leave a blank 32 bytes (the length block with 0).
                            mstore(
                                0x40,
                                and(
                                    add(add(end, iszero(add(length, mload(_preBytes)))), 31),
                                    not(31) // Round down to the nearest 32 bytes.
                                )
                            )
                        }
                        return tempBytes;
                    }
                    function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
                        assembly {
                            // Read the first 32 bytes of _preBytes storage, which is the length
                            // of the array. (We don't need to use the offset into the slot
                            // because arrays use the entire slot.)
                            let fslot := sload(_preBytes.slot)
                            // Arrays of 31 bytes or less have an even value in their slot,
                            // while longer arrays have an odd value. The actual length is
                            // the slot divided by two for odd values, and the lowest order
                            // byte divided by two for even values.
                            // If the slot is even, bitwise and the slot with 255 and divide by
                            // two to get the length. If the slot is odd, bitwise and the slot
                            // with -1 and divide by two.
                            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                            let mlength := mload(_postBytes)
                            let newlength := add(slength, mlength)
                            // slength can contain both the length and contents of the array
                            // if length < 32 bytes so let's prepare for that
                            // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                            switch add(lt(slength, 32), lt(newlength, 32))
                            case 2 {
                                // Since the new array still fits in the slot, we just need to
                                // update the contents of the slot.
                                // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
                                sstore(
                                    _preBytes.slot,
                                    // all the modifications to the slot are inside this
                                    // next block
                                    add(
                                        // we can just add to the slot contents because the
                                        // bytes we want to change are the LSBs
                                        fslot,
                                        add(
                                            mul(
                                                div(
                                                    // load the bytes from memory
                                                    mload(add(_postBytes, 0x20)),
                                                    // zero all bytes to the right
                                                    exp(0x100, sub(32, mlength))
                                                ),
                                                // and now shift left the number of bytes to
                                                // leave space for the length in the slot
                                                exp(0x100, sub(32, newlength))
                                            ),
                                            // increase length by the double of the memory
                                            // bytes length
                                            mul(mlength, 2)
                                        )
                                    )
                                )
                            }
                            case 1 {
                                // The stored value fits in the slot, but the combined value
                                // will exceed it.
                                // get the keccak hash to get the contents of the array
                                mstore(0x0, _preBytes.slot)
                                let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                                // save new length
                                sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                                // The contents of the _postBytes array start 32 bytes into
                                // the structure. Our first read should obtain the `submod`
                                // bytes that can fit into the unused space in the last word
                                // of the stored array. To get this, we read 32 bytes starting
                                // from `submod`, so the data we read overlaps with the array
                                // contents by `submod` bytes. Masking the lowest-order
                                // `submod` bytes allows us to add that value directly to the
                                // stored value.
                                let submod := sub(32, slength)
                                let mc := add(_postBytes, submod)
                                let end := add(_postBytes, mlength)
                                let mask := sub(exp(0x100, submod), 1)
                                sstore(
                                    sc,
                                    add(
                                        and(fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00),
                                        and(mload(mc), mask)
                                    )
                                )
                                for {
                                    mc := add(mc, 0x20)
                                    sc := add(sc, 1)
                                } lt(mc, end) {
                                    sc := add(sc, 1)
                                    mc := add(mc, 0x20)
                                } {
                                    sstore(sc, mload(mc))
                                }
                                mask := exp(0x100, sub(mc, end))
                                sstore(sc, mul(div(mload(mc), mask), mask))
                            }
                            default {
                                // get the keccak hash to get the contents of the array
                                mstore(0x0, _preBytes.slot)
                                // Start copying to the last used word of the stored array.
                                let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                                // save new length
                                sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                                // Copy over the first `submod` bytes of the new data as in
                                // case 1 above.
                                let slengthmod := mod(slength, 32)
                                let submod := sub(32, slengthmod)
                                let mc := add(_postBytes, submod)
                                let end := add(_postBytes, mlength)
                                let mask := sub(exp(0x100, submod), 1)
                                sstore(sc, add(sload(sc), and(mload(mc), mask)))
                                for {
                                    sc := add(sc, 1)
                                    mc := add(mc, 0x20)
                                } lt(mc, end) {
                                    sc := add(sc, 1)
                                    mc := add(mc, 0x20)
                                } {
                                    sstore(sc, mload(mc))
                                }
                                mask := exp(0x100, sub(mc, end))
                                sstore(sc, mul(div(mload(mc), mask), mask))
                            }
                        }
                    }
                    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;
                    }
                    function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
                        if (_bytes.length < _start + 1) {
                            revert UintOutOfBounds();
                        }
                        uint8 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x1), _start))
                        }
                        return tempUint;
                    }
                    function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
                        if (_bytes.length < _start + 2) {
                            revert UintOutOfBounds();
                        }
                        uint16 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x2), _start))
                        }
                        return tempUint;
                    }
                    function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
                        if (_bytes.length < _start + 4) {
                            revert UintOutOfBounds();
                        }
                        uint32 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x4), _start))
                        }
                        return tempUint;
                    }
                    function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
                        if (_bytes.length < _start + 8) {
                            revert UintOutOfBounds();
                        }
                        uint64 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x8), _start))
                        }
                        return tempUint;
                    }
                    function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
                        if (_bytes.length < _start + 12) {
                            revert UintOutOfBounds();
                        }
                        uint96 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0xc), _start))
                        }
                        return tempUint;
                    }
                    function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
                        if (_bytes.length < _start + 16) {
                            revert UintOutOfBounds();
                        }
                        uint128 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x10), _start))
                        }
                        return tempUint;
                    }
                    function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
                        if (_bytes.length < _start + 32) {
                            revert UintOutOfBounds();
                        }
                        uint256 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x20), _start))
                        }
                        return tempUint;
                    }
                    function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
                        if (_bytes.length < _start + 32) {
                            revert UintOutOfBounds();
                        }
                        bytes32 tempBytes32;
                        assembly {
                            tempBytes32 := mload(add(add(_bytes, 0x20), _start))
                        }
                        return tempBytes32;
                    }
                    function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
                        bool success = true;
                        assembly {
                            let length := mload(_preBytes)
                            // if lengths don't match the arrays are not equal
                            switch eq(length, mload(_postBytes))
                            case 1 {
                                // cb is a circuit breaker in the for loop since there's
                                //  no said feature for inline assembly loops
                                // cb = 1 - don't breaker
                                // cb = 0 - break
                                let cb := 1
                                let mc := add(_preBytes, 0x20)
                                let end := add(mc, length)
                                for {
                                    let cc := add(_postBytes, 0x20)
                                    // the next line is the loop condition:
                                    // while(uint256(mc < end) + cb == 2)
                                } eq(add(lt(mc, end), cb), 2) {
                                    mc := add(mc, 0x20)
                                    cc := add(cc, 0x20)
                                } {
                                    // if any of these checks fails then arrays are not equal
                                    if iszero(eq(mload(mc), mload(cc))) {
                                        // unsuccess:
                                        success := 0
                                        cb := 0
                                    }
                                }
                            }
                            default {
                                // unsuccess:
                                success := 0
                            }
                        }
                        return success;
                    }
                    function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {
                        bool success = true;
                        assembly {
                            // we know _preBytes_offset is 0
                            let fslot := sload(_preBytes.slot)
                            // Decode the length of the stored array like in concatStorage().
                            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                            let mlength := mload(_postBytes)
                            // if lengths don't match the arrays are not equal
                            switch eq(slength, mlength)
                            case 1 {
                                // slength can contain both the length and contents of the array
                                // if length < 32 bytes so let's prepare for that
                                // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                                if iszero(iszero(slength)) {
                                    switch lt(slength, 32)
                                    case 1 {
                                        // blank the last byte which is the length
                                        fslot := mul(div(fslot, 0x100), 0x100)
                                        if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
                                            // unsuccess:
                                            success := 0
                                        }
                                    }
                                    default {
                                        // cb is a circuit breaker in the for loop since there's
                                        //  no said feature for inline assembly loops
                                        // cb = 1 - don't breaker
                                        // cb = 0 - break
                                        let cb := 1
                                        // get the keccak hash to get the contents of the array
                                        mstore(0x0, _preBytes.slot)
                                        let sc := keccak256(0x0, 0x20)
                                        let mc := add(_postBytes, 0x20)
                                        let end := add(mc, mlength)
                                        // the next line is the loop condition:
                                        // while(uint256(mc < end) + cb == 2)
                                        // solhint-disable-next-line no-empty-blocks
                                        for {
                                        } eq(add(lt(mc, end), cb), 2) {
                                            sc := add(sc, 1)
                                            mc := add(mc, 0x20)
                                        } {
                                            if iszero(eq(sload(sc), mload(mc))) {
                                                // unsuccess:
                                                success := 0
                                                cb := 0
                                            }
                                        }
                                    }
                                }
                            }
                            default {
                                // unsuccess:
                                success := 0
                            }
                        }
                        return success;
                    }
                }
                // 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
                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);
                    }
                }
                

                File 2 of 5: FeeCollector
                // SPDX-License-Identifier: UNLICENSED
                pragma solidity ^0.8.17;
                import { LibAsset } from "../Libraries/LibAsset.sol";
                import { TransferrableOwnership } from "../Helpers/TransferrableOwnership.sol";
                import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol";
                /// @title Fee Collector
                /// @author LI.FI (https://li.fi)
                /// @notice Provides functionality for collecting integrator fees
                /// @custom:version 1.0.1
                contract FeeCollector is TransferrableOwnership {
                    /// State ///
                    // Integrator -> TokenAddress -> Balance
                    mapping(address => mapping(address => uint256)) private _balances;
                    // TokenAddress -> Balance
                    mapping(address => uint256) private _lifiBalances;
                    /// Errors ///
                    error TransferFailure();
                    error NotEnoughNativeForFees();
                    /// Events ///
                    event FeesCollected(
                        address indexed _token,
                        address indexed _integrator,
                        uint256 _integratorFee,
                        uint256 _lifiFee
                    );
                    event FeesWithdrawn(
                        address indexed _token,
                        address indexed _to,
                        uint256 _amount
                    );
                    event LiFiFeesWithdrawn(
                        address indexed _token,
                        address indexed _to,
                        uint256 _amount
                    );
                    /// Constructor ///
                    // solhint-disable-next-line no-empty-blocks
                    constructor(address _owner) TransferrableOwnership(_owner) {}
                    /// External Methods ///
                    /// @notice Collects fees for the integrator
                    /// @param tokenAddress address of the token to collect fees for
                    /// @param integratorFee amount of fees to collect going to the integrator
                    /// @param lifiFee amount of fees to collect going to lifi
                    /// @param integratorAddress address of the integrator
                    function collectTokenFees(
                        address tokenAddress,
                        uint256 integratorFee,
                        uint256 lifiFee,
                        address integratorAddress
                    ) external {
                        LibAsset.depositAsset(tokenAddress, integratorFee + lifiFee);
                        _balances[integratorAddress][tokenAddress] += integratorFee;
                        _lifiBalances[tokenAddress] += lifiFee;
                        emit FeesCollected(
                            tokenAddress,
                            integratorAddress,
                            integratorFee,
                            lifiFee
                        );
                    }
                    /// @notice Collects fees for the integrator in native token
                    /// @param integratorFee amount of fees to collect going to the integrator
                    /// @param lifiFee amount of fees to collect going to lifi
                    /// @param integratorAddress address of the integrator
                    function collectNativeFees(
                        uint256 integratorFee,
                        uint256 lifiFee,
                        address integratorAddress
                    ) external payable {
                        if (msg.value < integratorFee + lifiFee)
                            revert NotEnoughNativeForFees();
                        _balances[integratorAddress][LibAsset.NULL_ADDRESS] += integratorFee;
                        _lifiBalances[LibAsset.NULL_ADDRESS] += lifiFee;
                        uint256 remaining = msg.value - (integratorFee + lifiFee);
                        // Prevent extra native token from being locked in the contract
                        if (remaining > 0) {
                            // solhint-disable-next-line avoid-low-level-calls
                            SafeTransferLib.safeTransferETH(msg.sender, remaining);
                        }
                        emit FeesCollected(
                            LibAsset.NULL_ADDRESS,
                            integratorAddress,
                            integratorFee,
                            lifiFee
                        );
                    }
                    /// @notice Withdraw fees and sends to the integrator
                    /// @param tokenAddress address of the token to withdraw fees for
                    function withdrawIntegratorFees(address tokenAddress) external {
                        uint256 balance = _balances[msg.sender][tokenAddress];
                        if (balance == 0) {
                            return;
                        }
                        _balances[msg.sender][tokenAddress] = 0;
                        LibAsset.transferAsset(tokenAddress, payable(msg.sender), balance);
                        emit FeesWithdrawn(tokenAddress, msg.sender, balance);
                    }
                    /// @notice Batch withdraw fees and sends to the integrator
                    /// @param tokenAddresses addresses of the tokens to withdraw fees for
                    function batchWithdrawIntegratorFees(
                        address[] memory tokenAddresses
                    ) external {
                        uint256 length = tokenAddresses.length;
                        uint256 balance;
                        for (uint256 i = 0; i < length; ) {
                            balance = _balances[msg.sender][tokenAddresses[i]];
                            if (balance != 0) {
                                _balances[msg.sender][tokenAddresses[i]] = 0;
                                LibAsset.transferAsset(
                                    tokenAddresses[i],
                                    payable(msg.sender),
                                    balance
                                );
                                emit FeesWithdrawn(tokenAddresses[i], msg.sender, balance);
                            }
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /// @notice Withdraws fees and sends to lifi
                    /// @param tokenAddress address of the token to withdraw fees for
                    function withdrawLifiFees(address tokenAddress) external onlyOwner {
                        uint256 balance = _lifiBalances[tokenAddress];
                        if (balance == 0) {
                            return;
                        }
                        _lifiBalances[tokenAddress] = 0;
                        LibAsset.transferAsset(tokenAddress, payable(msg.sender), balance);
                        emit LiFiFeesWithdrawn(tokenAddress, msg.sender, balance);
                    }
                    /// @notice Batch withdraws fees and sends to lifi
                    /// @param tokenAddresses addresses of the tokens to withdraw fees for
                    function batchWithdrawLifiFees(
                        address[] memory tokenAddresses
                    ) external onlyOwner {
                        uint256 length = tokenAddresses.length;
                        uint256 balance;
                        for (uint256 i = 0; i < length; ) {
                            balance = _lifiBalances[tokenAddresses[i]];
                            _lifiBalances[tokenAddresses[i]] = 0;
                            LibAsset.transferAsset(
                                tokenAddresses[i],
                                payable(msg.sender),
                                balance
                            );
                            emit LiFiFeesWithdrawn(tokenAddresses[i], msg.sender, balance);
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /// @notice Returns the balance of the integrator
                    /// @param integratorAddress address of the integrator
                    /// @param tokenAddress address of the token to get the balance of
                    function getTokenBalance(
                        address integratorAddress,
                        address tokenAddress
                    ) external view returns (uint256) {
                        return _balances[integratorAddress][tokenAddress];
                    }
                    /// @notice Returns the balance of lifi
                    /// @param tokenAddress address of the token to get the balance of
                    function getLifiTokenBalance(
                        address tokenAddress
                    ) external view returns (uint256) {
                        return _lifiBalances[tokenAddress];
                    }
                }
                // SPDX-License-Identifier: UNLICENSED
                pragma solidity ^0.8.17;
                import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                import { LibSwap } from "./LibSwap.sol";
                import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol";
                // solhint-disable-next-line max-line-length
                import { InvalidReceiver, NullAddrIsNotAValidSpender, InvalidAmount, NullAddrIsNotAnERC20Token } from "../Errors/GenericErrors.sol";
                /// @title LibAsset
                /// @author LI.FI (https://li.fi)
                /// @custom:version 2.1.2
                /// @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 {
                    using SafeTransferLib for address;
                    using SafeTransferLib for address payable;
                    /// @dev All native assets use the empty address for their asset id
                    ///      by convention
                    address internal constant NULL_ADDRESS = address(0);
                    /// @dev EIP-7702 delegation designator prefix for Account Abstraction
                    bytes3 internal constant DELEGATION_DESIGNATOR = 0xef0100;
                    /// @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 (returns 0 if assetId does not exist)
                    function getOwnBalance(address assetId) internal view returns (uint256) {
                        return
                            isNativeAsset(assetId)
                                ? address(this).balance
                                : assetId.balanceOf(address(this));
                    }
                    /// @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 {
                        if (isNativeAsset(assetId)) {
                            transferNativeAsset(recipient, amount);
                        } else {
                            transferERC20(assetId, recipient, amount);
                        }
                    }
                    /// @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 {
                        // make sure a meaningful receiver address was provided
                        if (recipient == NULL_ADDRESS) revert InvalidReceiver();
                        // transfer native asset (will revert if target reverts or contract has insufficient balance)
                        recipient.safeTransferETH(amount);
                    }
                    /// @notice Transfers tokens from the inheriting contract to a given recipient
                    /// @param assetId Token address to transfer
                    /// @param recipient Address to send tokens to
                    /// @param amount Amount to send to given recipient
                    function transferERC20(
                        address assetId,
                        address recipient,
                        uint256 amount
                    ) internal {
                        // make sure a meaningful receiver address was provided
                        if (recipient == NULL_ADDRESS) {
                            revert InvalidReceiver();
                        }
                        // transfer ERC20 assets (will revert if target reverts or contract has insufficient balance)
                        assetId.safeTransfer(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 recipient Address of recipient/spender
                    /// @param amount Amount to transfer from owner to spender
                    function transferFromERC20(
                        address assetId,
                        address from,
                        address recipient,
                        uint256 amount
                    ) internal {
                        // check if native asset
                        if (isNativeAsset(assetId)) {
                            revert NullAddrIsNotAnERC20Token();
                        }
                        // make sure a meaningful receiver address was provided
                        if (recipient == NULL_ADDRESS) {
                            revert InvalidReceiver();
                        }
                        // transfer ERC20 assets (will revert if target reverts or contract has insufficient balance)
                        assetId.safeTransferFrom(from, recipient, amount);
                    }
                    /// @notice Pulls tokens from msg.sender
                    /// @param assetId Token address to transfer
                    /// @param amount Amount to transfer from owner
                    function depositAsset(address assetId, uint256 amount) internal {
                        // make sure a meaningful amount was provided
                        if (amount == 0) revert InvalidAmount();
                        // check if native asset
                        if (isNativeAsset(assetId)) {
                            // ensure msg.value is equal or greater than amount
                            if (msg.value < amount) revert InvalidAmount();
                        } else {
                            // transfer ERC20 assets (will revert if target reverts or contract has insufficient balance)
                            assetId.safeTransferFrom(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 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 allowance amount required for current transaction
                    function maxApproveERC20(
                        IERC20 assetId,
                        address spender,
                        uint256 amount
                    ) internal {
                        approveERC20(assetId, spender, amount, type(uint256).max);
                    }
                    /// @notice If the current allowance is insufficient, the allowance for a given spender
                    ///         is set to the amount provided
                    /// @param assetId Token address to transfer
                    /// @param spender Address to give spend approval to
                    /// @param requiredAllowance Allowance required for current transaction
                    /// @param setAllowanceTo The amount the allowance should be set to if current allowance is insufficient
                    function approveERC20(
                        IERC20 assetId,
                        address spender,
                        uint256 requiredAllowance,
                        uint256 setAllowanceTo
                    ) internal {
                        if (isNativeAsset(address(assetId))) {
                            return;
                        }
                        // make sure a meaningful spender address was provided
                        if (spender == NULL_ADDRESS) {
                            revert NullAddrIsNotAValidSpender();
                        }
                        // check if allowance is sufficient, otherwise set allowance to provided amount
                        // If the initial attempt to approve fails, attempts to reset the approved amount to zero,
                        // then retries the approval again (some tokens, e.g. USDT, requires this).
                        // Reverts upon failure
                        if (assetId.allowance(address(this), spender) < requiredAllowance) {
                            address(assetId).safeApproveWithRetry(spender, setAllowanceTo);
                        }
                    }
                    /// @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 == NULL_ADDRESS;
                    }
                    /// @notice Checks if the given address is a contract
                    ///         Returns true for any account with runtime code (excluding EIP-7702 accounts).
                    ///         For EIP-7702 accounts, checks if code size is exactly 23 bytes (delegation format).
                    ///         Limitations:
                    ///         - Cannot distinguish between EOA and self-destructed contract
                    /// @param account The address to be checked
                    function isContract(address account) internal view returns (bool) {
                        uint256 size;
                        assembly {
                            size := extcodesize(account)
                        }
                        // Return true only for regular contracts (size > 23)
                        // EIP-7702 delegated accounts (size == 23) are still EOAs, not contracts
                        return size > 23;
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                /// @custom:version 1.0.0
                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: MIT
                pragma solidity ^0.8.4;
                /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
                /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
                /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
                /// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
                ///
                /// @dev Note:
                /// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
                /// - For ERC20s, this implementation won't check that a token has code,
                ///   responsibility is delegated to the caller.
                library SafeTransferLib {
                    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                    /*                       CUSTOM ERRORS                        */
                    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                    /// @dev The ETH transfer has failed.
                    error ETHTransferFailed();
                    /// @dev The ERC20 `transferFrom` has failed.
                    error TransferFromFailed();
                    /// @dev The ERC20 `transfer` has failed.
                    error TransferFailed();
                    /// @dev The ERC20 `approve` has failed.
                    error ApproveFailed();
                    /// @dev The Permit2 operation has failed.
                    error Permit2Failed();
                    /// @dev The Permit2 amount must be less than `2**160 - 1`.
                    error Permit2AmountOverflow();
                    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                    /*                         CONSTANTS                          */
                    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                    /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
                    uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
                    /// @dev Suggested gas stipend for contract receiving ETH to perform a few
                    /// storage reads and writes, but low enough to prevent griefing.
                    uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
                    /// @dev The unique EIP-712 domain domain separator for the DAI token contract.
                    bytes32 internal constant DAI_DOMAIN_SEPARATOR =
                        0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
                    /// @dev The address for the WETH9 contract on Ethereum mainnet.
                    address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
                    /// @dev The canonical Permit2 address.
                    /// [Github](https://github.com/Uniswap/permit2)
                    /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
                    address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
                    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                    /*                       ETH OPERATIONS                       */
                    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                    // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
                    //
                    // The regular variants:
                    // - Forwards all remaining gas to the target.
                    // - Reverts if the target reverts.
                    // - Reverts if the current contract has insufficient balance.
                    //
                    // The force variants:
                    // - Forwards with an optional gas stipend
                    //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
                    // - If the target reverts, or if the gas stipend is exhausted,
                    //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
                    //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
                    // - Reverts if the current contract has insufficient balance.
                    //
                    // The try variants:
                    // - Forwards with a mandatory gas stipend.
                    // - Instead of reverting, returns whether the transfer succeeded.
                    /// @dev Sends `amount` (in wei) ETH to `to`.
                    function safeTransferETH(address to, uint256 amount) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                revert(0x1c, 0x04)
                            }
                        }
                    }
                    /// @dev Sends all the ETH in the current contract to `to`.
                    function safeTransferAllETH(address to) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            // Transfer all the ETH and check if it succeeded or not.
                            if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                revert(0x1c, 0x04)
                            }
                        }
                    }
                    /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
                    function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            if lt(selfbalance(), amount) {
                                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                revert(0x1c, 0x04)
                            }
                            if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                mstore(0x00, to) // Store the address in scratch space.
                                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                            }
                        }
                    }
                    /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
                    function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                mstore(0x00, to) // Store the address in scratch space.
                                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                            }
                        }
                    }
                    /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
                    function forceSafeTransferETH(address to, uint256 amount) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            if lt(selfbalance(), amount) {
                                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                revert(0x1c, 0x04)
                            }
                            if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                mstore(0x00, to) // Store the address in scratch space.
                                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                            }
                        }
                    }
                    /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
                    function forceSafeTransferAllETH(address to) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            // forgefmt: disable-next-item
                            if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                mstore(0x00, to) // Store the address in scratch space.
                                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                            }
                        }
                    }
                    /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
                    function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
                        internal
                        returns (bool success)
                    {
                        /// @solidity memory-safe-assembly
                        assembly {
                            success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
                        }
                    }
                    /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
                    function trySafeTransferAllETH(address to, uint256 gasStipend)
                        internal
                        returns (bool success)
                    {
                        /// @solidity memory-safe-assembly
                        assembly {
                            success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
                        }
                    }
                    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                    /*                      ERC20 OPERATIONS                      */
                    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                    /// Reverts upon failure.
                    ///
                    /// The `from` account must have at least `amount` approved for
                    /// the current contract to manage.
                    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            let m := mload(0x40) // Cache the free memory pointer.
                            mstore(0x60, amount) // Store the `amount` argument.
                            mstore(0x40, to) // Store the `to` argument.
                            mstore(0x2c, shl(96, from)) // Store the `from` argument.
                            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
                            // Perform the transfer, reverting upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                    call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                )
                            ) {
                                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                revert(0x1c, 0x04)
                            }
                            mstore(0x60, 0) // Restore the zero slot to zero.
                            mstore(0x40, m) // Restore the free memory pointer.
                        }
                    }
                    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                    ///
                    /// The `from` account must have at least `amount` approved for the current contract to manage.
                    function trySafeTransferFrom(address token, address from, address to, uint256 amount)
                        internal
                        returns (bool success)
                    {
                        /// @solidity memory-safe-assembly
                        assembly {
                            let m := mload(0x40) // Cache the free memory pointer.
                            mstore(0x60, amount) // Store the `amount` argument.
                            mstore(0x40, to) // Store the `to` argument.
                            mstore(0x2c, shl(96, from)) // Store the `from` argument.
                            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
                            success :=
                                and( // The arguments of `and` are evaluated from right to left.
                                    or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                    call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                )
                            mstore(0x60, 0) // Restore the zero slot to zero.
                            mstore(0x40, m) // Restore the free memory pointer.
                        }
                    }
                    /// @dev Sends all of ERC20 `token` from `from` to `to`.
                    /// Reverts upon failure.
                    ///
                    /// The `from` account must have their entire balance approved for the current contract to manage.
                    function safeTransferAllFrom(address token, address from, address to)
                        internal
                        returns (uint256 amount)
                    {
                        /// @solidity memory-safe-assembly
                        assembly {
                            let m := mload(0x40) // Cache the free memory pointer.
                            mstore(0x40, to) // Store the `to` argument.
                            mstore(0x2c, shl(96, from)) // Store the `from` argument.
                            mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
                            // Read the balance, reverting upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                    staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                                )
                            ) {
                                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                revert(0x1c, 0x04)
                            }
                            mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
                            amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
                            // Perform the transfer, reverting upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                    call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                )
                            ) {
                                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                revert(0x1c, 0x04)
                            }
                            mstore(0x60, 0) // Restore the zero slot to zero.
                            mstore(0x40, m) // Restore the free memory pointer.
                        }
                    }
                    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
                    /// Reverts upon failure.
                    function safeTransfer(address token, address to, uint256 amount) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            mstore(0x14, to) // Store the `to` argument.
                            mstore(0x34, amount) // Store the `amount` argument.
                            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
                            // Perform the transfer, reverting upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                )
                            ) {
                                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                revert(0x1c, 0x04)
                            }
                            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                        }
                    }
                    /// @dev Sends all of ERC20 `token` from the current contract to `to`.
                    /// Reverts upon failure.
                    function safeTransferAll(address token, address to) internal returns (uint256 amount) {
                        /// @solidity memory-safe-assembly
                        assembly {
                            mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
                            mstore(0x20, address()) // Store the address of the current contract.
                            // Read the balance, reverting upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                    staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                                )
                            ) {
                                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                revert(0x1c, 0x04)
                            }
                            mstore(0x14, to) // Store the `to` argument.
                            amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
                            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
                            // Perform the transfer, reverting upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                )
                            ) {
                                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                revert(0x1c, 0x04)
                            }
                            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                        }
                    }
                    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
                    /// Reverts upon failure.
                    function safeApprove(address token, address to, uint256 amount) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            mstore(0x14, to) // Store the `to` argument.
                            mstore(0x34, amount) // Store the `amount` argument.
                            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                            // Perform the approval, reverting upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                )
                            ) {
                                mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                                revert(0x1c, 0x04)
                            }
                            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                        }
                    }
                    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
                    /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
                    /// then retries the approval again (some tokens, e.g. USDT, requires this).
                    /// Reverts upon failure.
                    function safeApproveWithRetry(address token, address to, uint256 amount) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            mstore(0x14, to) // Store the `to` argument.
                            mstore(0x34, amount) // Store the `amount` argument.
                            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                            // Perform the approval, retrying upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                )
                            ) {
                                mstore(0x34, 0) // Store 0 for the `amount`.
                                mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                                pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                                mstore(0x34, amount) // Store back the original `amount`.
                                // Retry the approval, reverting upon failure.
                                if iszero(
                                    and(
                                        or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                        call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                    )
                                ) {
                                    mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                                    revert(0x1c, 0x04)
                                }
                            }
                            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                        }
                    }
                    /// @dev Returns the amount of ERC20 `token` owned by `account`.
                    /// Returns zero if the `token` does not exist.
                    function balanceOf(address token, address account) internal view returns (uint256 amount) {
                        /// @solidity memory-safe-assembly
                        assembly {
                            mstore(0x14, account) // Store the `account` argument.
                            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
                            amount :=
                                mul( // The arguments of `mul` are evaluated from right to left.
                                    mload(0x20),
                                    and( // The arguments of `and` are evaluated from right to left.
                                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                        staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                                    )
                                )
                        }
                    }
                    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                    /// If the initial attempt fails, try to use Permit2 to transfer the token.
                    /// Reverts upon failure.
                    ///
                    /// The `from` account must have at least `amount` approved for the current contract to manage.
                    function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
                        if (!trySafeTransferFrom(token, from, to, amount)) {
                            permit2TransferFrom(token, from, to, amount);
                        }
                    }
                    /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
                    /// Reverts upon failure.
                    function permit2TransferFrom(address token, address from, address to, uint256 amount)
                        internal
                    {
                        /// @solidity memory-safe-assembly
                        assembly {
                            let m := mload(0x40)
                            mstore(add(m, 0x74), shr(96, shl(96, token)))
                            mstore(add(m, 0x54), amount)
                            mstore(add(m, 0x34), to)
                            mstore(add(m, 0x20), shl(96, from))
                            // `transferFrom(address,address,uint160,address)`.
                            mstore(m, 0x36c78516000000000000000000000000)
                            let p := PERMIT2
                            let exists := eq(chainid(), 1)
                            if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
                            if iszero(and(call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00), exists)) {
                                mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                                revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
                            }
                        }
                    }
                    /// @dev Permit a user to spend a given amount of
                    /// another user's tokens via native EIP-2612 permit if possible, falling
                    /// back to Permit2 if native permit fails or is not implemented on the token.
                    function permit2(
                        address token,
                        address owner,
                        address spender,
                        uint256 amount,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal {
                        bool success;
                        /// @solidity memory-safe-assembly
                        assembly {
                            for {} shl(96, xor(token, WETH9)) {} {
                                mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                                if iszero(
                                    and( // The arguments of `and` are evaluated from right to left.
                                        lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                                        // Gas stipend to limit gas burn for tokens that don't refund gas when
                                        // an non-existing function is called. 5K should be enough for a SLOAD.
                                        staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                                    )
                                ) { break }
                                // After here, we can be sure that token is a contract.
                                let m := mload(0x40)
                                mstore(add(m, 0x34), spender)
                                mstore(add(m, 0x20), shl(96, owner))
                                mstore(add(m, 0x74), deadline)
                                if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                                    mstore(0x14, owner)
                                    mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                                    mstore(add(m, 0x94), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                                    mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                                    // `nonces` is already at `add(m, 0x54)`.
                                    // `1` is already stored at `add(m, 0x94)`.
                                    mstore(add(m, 0xb4), and(0xff, v))
                                    mstore(add(m, 0xd4), r)
                                    mstore(add(m, 0xf4), s)
                                    success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                                    break
                                }
                                mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                                mstore(add(m, 0x54), amount)
                                mstore(add(m, 0x94), and(0xff, v))
                                mstore(add(m, 0xb4), r)
                                mstore(add(m, 0xd4), s)
                                success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                                break
                            }
                        }
                        if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
                    }
                    /// @dev Simple permit on the Permit2 contract.
                    function simplePermit2(
                        address token,
                        address owner,
                        address spender,
                        uint256 amount,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            let m := mload(0x40)
                            mstore(m, 0x927da105) // `allowance(address,address,address)`.
                            {
                                let addressMask := shr(96, not(0))
                                mstore(add(m, 0x20), and(addressMask, owner))
                                mstore(add(m, 0x40), and(addressMask, token))
                                mstore(add(m, 0x60), and(addressMask, spender))
                                mstore(add(m, 0xc0), and(addressMask, spender))
                            }
                            let p := mul(PERMIT2, iszero(shr(160, amount)))
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                                    staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                                )
                            ) {
                                mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                                revert(add(0x18, shl(2, iszero(p))), 0x04)
                            }
                            mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
                            // `owner` is already `add(m, 0x20)`.
                            // `token` is already at `add(m, 0x40)`.
                            mstore(add(m, 0x60), amount)
                            mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
                            // `nonce` is already at `add(m, 0xa0)`.
                            // `spender` is already at `add(m, 0xc0)`.
                            mstore(add(m, 0xe0), deadline)
                            mstore(add(m, 0x100), 0x100) // `signature` offset.
                            mstore(add(m, 0x120), 0x41) // `signature` length.
                            mstore(add(m, 0x140), r)
                            mstore(add(m, 0x160), s)
                            mstore(add(m, 0x180), shl(248, v))
                            if iszero(call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00)) {
                                mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                                revert(0x1c, 0x04)
                            }
                        }
                    }
                }
                // 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: LGPL-3.0-only
                pragma solidity ^0.8.17;
                import { LibAsset } from "./LibAsset.sol";
                import { LibUtil } from "./LibUtil.sol";
                import { InvalidContract, NoSwapFromZeroBalance } from "../Errors/GenericErrors.sol";
                import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                /// @title LibSwap
                /// @custom:version 1.1.0
                /// @notice This library contains functionality to execute mostly swaps but also
                ///         other calls such as fee collection, token wrapping/unwrapping or
                ///         sending gas to destination chain
                library LibSwap {
                    /// @notice Struct containing all necessary data to execute a swap or generic call
                    /// @param callTo The address of the contract to call for executing the swap
                    /// @param approveTo The address that will receive token approval (can be different than callTo for some DEXs)
                    /// @param sendingAssetId The address of the token being sent
                    /// @param receivingAssetId The address of the token expected to be received
                    /// @param fromAmount The exact amount of the sending asset to be used in the call
                    /// @param callData Encoded function call data to be sent to the `callTo` contract
                    /// @param requiresDeposit A flag indicating whether the tokens must be deposited (pulled) before the call
                    struct SwapData {
                        address callTo;
                        address approveTo;
                        address sendingAssetId;
                        address receivingAssetId;
                        uint256 fromAmount;
                        bytes callData;
                        bool requiresDeposit;
                    }
                    /// @notice Emitted after a successful asset swap or related operation
                    /// @param transactionId    The unique identifier associated with the swap operation
                    /// @param dex              The address of the DEX or contract that handled the swap
                    /// @param fromAssetId      The address of the token that was sent
                    /// @param toAssetId        The address of the token that was received
                    /// @param fromAmount       The amount of `fromAssetId` sent
                    /// @param toAmount         The amount of `toAssetId` received
                    /// @param timestamp        The timestamp when the swap was executed
                    event AssetSwapped(
                        bytes32 transactionId,
                        address dex,
                        address fromAssetId,
                        address toAssetId,
                        uint256 fromAmount,
                        uint256 toAmount,
                        uint256 timestamp
                    );
                    function swap(bytes32 transactionId, SwapData calldata _swap) internal {
                        // make sure callTo is a contract
                        if (!LibAsset.isContract(_swap.callTo)) revert InvalidContract();
                        // make sure that fromAmount is not 0
                        uint256 fromAmount = _swap.fromAmount;
                        if (fromAmount == 0) revert NoSwapFromZeroBalance();
                        // determine how much native value to send with the swap call
                        uint256 nativeValue = LibAsset.isNativeAsset(_swap.sendingAssetId)
                            ? _swap.fromAmount
                            : 0;
                        // store initial balance (required for event emission)
                        uint256 initialReceivingAssetBalance = LibAsset.getOwnBalance(
                            _swap.receivingAssetId
                        );
                        // max approve (if ERC20)
                        if (nativeValue == 0) {
                            LibAsset.maxApproveERC20(
                                IERC20(_swap.sendingAssetId),
                                _swap.approveTo,
                                _swap.fromAmount
                            );
                        }
                        // we used to have a sending asset balance check here (initialSendingAssetBalance >= _swap.fromAmount)
                        // this check was removed to allow for more flexibility with rebasing/fee-taking tokens
                        // the general assumption is that if not enough tokens are available to execute the calldata,
                        // the transaction will fail anyway
                        // the error message might not be as explicit though
                        // execute the swap
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, bytes memory res) = _swap.callTo.call{
                            value: nativeValue
                        }(_swap.callData);
                        if (!success) {
                            LibUtil.revertWith(res);
                        }
                        // get post-swap balance
                        uint256 newBalance = LibAsset.getOwnBalance(_swap.receivingAssetId);
                        // emit event
                        emit AssetSwapped(
                            transactionId,
                            _swap.callTo,
                            _swap.sendingAssetId,
                            _swap.receivingAssetId,
                            _swap.fromAmount,
                            newBalance > initialReceivingAssetBalance
                                ? newBalance - initialReceivingAssetBalance
                                : newBalance,
                            block.timestamp
                        );
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                /// @custom:version 1.0.2
                pragma solidity ^0.8.17;
                error AlreadyInitialized();
                error CannotAuthoriseSelf();
                error CannotBridgeToSameNetwork();
                error ContractCallNotAllowed();
                error CumulativeSlippageTooHigh(uint256 minAmount, uint256 receivedAmount);
                error DiamondIsPaused();
                error ETHTransferFailed();
                error ExternalCallFailed();
                error FunctionDoesNotExist();
                error InformationMismatch();
                error InsufficientBalance(uint256 required, uint256 balance);
                error InvalidAmount();
                error InvalidCallData();
                error InvalidConfig();
                error InvalidContract();
                error InvalidDestinationChain();
                error InvalidFallbackAddress();
                error InvalidNonEVMReceiver();
                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 TransferFromFailed();
                error UnAuthorized();
                error UnsupportedChainId(uint256 chainId);
                error WithdrawFailed();
                error ZeroAmount();
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity ^0.8.17;
                /// @title Interface for ERC-173 (Contract Ownership Standard)
                /// @author LI.FI (https://li.fi)
                /// Note: the ERC-165 identifier for this interface is 0x7f5828d0
                /// @custom:version 1.0.0
                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;
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                /// @custom:version 1.0.0
                pragma solidity ^0.8.17;
                // solhint-disable-next-line no-global-import
                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);
                    }
                    function revertWith(bytes memory data) internal pure {
                        assembly {
                            let dataSize := mload(data) // Load the size of the data
                            let dataPtr := add(data, 0x20) // Advance data pointer to the next word
                            revert(dataPtr, dataSize) // Revert with the given data
                        }
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                /// @custom:version 1.0.0
                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;
                        }
                        // solhint-disable-next-line gas-custom-errors
                        require(value == 0, "Strings: hex length insufficient");
                        return string(buffer);
                    }
                }
                

                File 3 of 5: MayanForwarder2
                // 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) (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
                // OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
                pragma solidity ^0.8.0;
                import "../IERC20.sol";
                import "../extensions/IERC20Permit.sol";
                import "../../../utils/Address.sol";
                /**
                 * @title SafeERC20
                 * @dev Wrappers around ERC20 operations that throw on failure (when the token
                 * contract returns false). Tokens that return no value (and instead revert or
                 * throw on failure) are also supported, non-reverting calls are assumed to be
                 * successful.
                 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                 */
                library SafeERC20 {
                    using Address for address;
                    /**
                     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
                     * non-reverting calls are assumed to be successful.
                     */
                    function safeTransfer(IERC20 token, address to, uint256 value) internal {
                        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                    }
                    /**
                     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
                     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
                     */
                    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                    }
                    /**
                     * @dev Deprecated. This function has issues similar to the ones found in
                     * {IERC20-approve}, and its usage is discouraged.
                     *
                     * Whenever possible, use {safeIncreaseAllowance} and
                     * {safeDecreaseAllowance} instead.
                     */
                    function safeApprove(IERC20 token, address spender, uint256 value) internal {
                        // safeApprove should only be called when setting an initial allowance,
                        // or when resetting it to zero. To increase and decrease it, use
                        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                        require(
                            (value == 0) || (token.allowance(address(this), spender) == 0),
                            "SafeERC20: approve from non-zero to non-zero allowance"
                        );
                        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                    }
                    /**
                     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
                     * non-reverting calls are assumed to be successful.
                     */
                    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                        uint256 oldAllowance = token.allowance(address(this), spender);
                        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
                    }
                    /**
                     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
                     * non-reverting calls are assumed to be successful.
                     */
                    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                        unchecked {
                            uint256 oldAllowance = token.allowance(address(this), spender);
                            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
                        }
                    }
                    /**
                     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
                     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
                     * to be set to zero before setting it to a non-zero value, such as USDT.
                     */
                    function forceApprove(IERC20 token, address spender, uint256 value) internal {
                        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
                        if (!_callOptionalReturnBool(token, approvalCall)) {
                            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
                            _callOptionalReturn(token, approvalCall);
                        }
                    }
                    /**
                     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
                     * Revert on invalid signature.
                     */
                    function safePermit(
                        IERC20Permit token,
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal {
                        uint256 nonceBefore = token.nonces(owner);
                        token.permit(owner, spender, value, deadline, v, r, s);
                        uint256 nonceAfter = token.nonces(owner);
                        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
                    }
                    /**
                     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                     * on the return value: the return value is optional (but if data is returned, it must not be false).
                     * @param token The token targeted by the call.
                     * @param data The call data (encoded using abi.encode or one of its variants).
                     */
                    function _callOptionalReturn(IERC20 token, bytes memory data) private {
                        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                        // the target address contains contract code and also asserts for success in the low-level call.
                        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                    }
                    /**
                     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                     * on the return value: the return value is optional (but if data is returned, it must not be false).
                     * @param token The token targeted by the call.
                     * @param data The call data (encoded using abi.encode or one of its variants).
                     *
                     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
                     */
                    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
                        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
                        // and not revert is the subcall reverts.
                        (bool success, bytes memory returndata) = address(token).call(data);
                        return
                            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
                    }
                }
                // 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: Unlicense
                /*
                 * @title Solidity Bytes Arrays Utils
                 * @author Gonçalo Sá <goncalo.sa@consensys.net>
                 *
                 * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
                 *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
                 */
                pragma solidity >=0.8.0 <0.9.0;
                library BytesLib {
                    function concat(
                        bytes memory _preBytes,
                        bytes memory _postBytes
                    )
                        internal
                        pure
                        returns (bytes memory)
                    {
                        bytes memory tempBytes;
                        assembly {
                            // Get a location of some free memory and store it in tempBytes as
                            // Solidity does for memory variables.
                            tempBytes := mload(0x40)
                            // Store the length of the first bytes array at the beginning of
                            // the memory for tempBytes.
                            let length := mload(_preBytes)
                            mstore(tempBytes, length)
                            // Maintain a memory counter for the current write location in the
                            // temp bytes array by adding the 32 bytes for the array length to
                            // the starting location.
                            let mc := add(tempBytes, 0x20)
                            // Stop copying when the memory counter reaches the length of the
                            // first bytes array.
                            let end := add(mc, length)
                            for {
                                // Initialize a copy counter to the start of the _preBytes data,
                                // 32 bytes into its memory.
                                let cc := add(_preBytes, 0x20)
                            } lt(mc, end) {
                                // Increase both counters by 32 bytes each iteration.
                                mc := add(mc, 0x20)
                                cc := add(cc, 0x20)
                            } {
                                // Write the _preBytes data into the tempBytes memory 32 bytes
                                // at a time.
                                mstore(mc, mload(cc))
                            }
                            // Add the length of _postBytes to the current length of tempBytes
                            // and store it as the new length in the first 32 bytes of the
                            // tempBytes memory.
                            length := mload(_postBytes)
                            mstore(tempBytes, add(length, mload(tempBytes)))
                            // Move the memory counter back from a multiple of 0x20 to the
                            // actual end of the _preBytes data.
                            mc := end
                            // Stop copying when the memory counter reaches the new combined
                            // length of the arrays.
                            end := add(mc, length)
                            for {
                                let cc := add(_postBytes, 0x20)
                            } lt(mc, end) {
                                mc := add(mc, 0x20)
                                cc := add(cc, 0x20)
                            } {
                                mstore(mc, mload(cc))
                            }
                            // Update the free-memory pointer by padding our last write location
                            // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
                            // next 32 byte block, then round down to the nearest multiple of
                            // 32. If the sum of the length of the two arrays is zero then add
                            // one before rounding down to leave a blank 32 bytes (the length block with 0).
                            mstore(0x40, and(
                              add(add(end, iszero(add(length, mload(_preBytes)))), 31),
                              not(31) // Round down to the nearest 32 bytes.
                            ))
                        }
                        return tempBytes;
                    }
                    function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
                        assembly {
                            // Read the first 32 bytes of _preBytes storage, which is the length
                            // of the array. (We don't need to use the offset into the slot
                            // because arrays use the entire slot.)
                            let fslot := sload(_preBytes.slot)
                            // Arrays of 31 bytes or less have an even value in their slot,
                            // while longer arrays have an odd value. The actual length is
                            // the slot divided by two for odd values, and the lowest order
                            // byte divided by two for even values.
                            // If the slot is even, bitwise and the slot with 255 and divide by
                            // two to get the length. If the slot is odd, bitwise and the slot
                            // with -1 and divide by two.
                            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                            let mlength := mload(_postBytes)
                            let newlength := add(slength, mlength)
                            // slength can contain both the length and contents of the array
                            // if length < 32 bytes so let's prepare for that
                            // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                            switch add(lt(slength, 32), lt(newlength, 32))
                            case 2 {
                                // Since the new array still fits in the slot, we just need to
                                // update the contents of the slot.
                                // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
                                sstore(
                                    _preBytes.slot,
                                    // all the modifications to the slot are inside this
                                    // next block
                                    add(
                                        // we can just add to the slot contents because the
                                        // bytes we want to change are the LSBs
                                        fslot,
                                        add(
                                            mul(
                                                div(
                                                    // load the bytes from memory
                                                    mload(add(_postBytes, 0x20)),
                                                    // zero all bytes to the right
                                                    exp(0x100, sub(32, mlength))
                                                ),
                                                // and now shift left the number of bytes to
                                                // leave space for the length in the slot
                                                exp(0x100, sub(32, newlength))
                                            ),
                                            // increase length by the double of the memory
                                            // bytes length
                                            mul(mlength, 2)
                                        )
                                    )
                                )
                            }
                            case 1 {
                                // The stored value fits in the slot, but the combined value
                                // will exceed it.
                                // get the keccak hash to get the contents of the array
                                mstore(0x0, _preBytes.slot)
                                let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                                // save new length
                                sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                                // The contents of the _postBytes array start 32 bytes into
                                // the structure. Our first read should obtain the `submod`
                                // bytes that can fit into the unused space in the last word
                                // of the stored array. To get this, we read 32 bytes starting
                                // from `submod`, so the data we read overlaps with the array
                                // contents by `submod` bytes. Masking the lowest-order
                                // `submod` bytes allows us to add that value directly to the
                                // stored value.
                                let submod := sub(32, slength)
                                let mc := add(_postBytes, submod)
                                let end := add(_postBytes, mlength)
                                let mask := sub(exp(0x100, submod), 1)
                                sstore(
                                    sc,
                                    add(
                                        and(
                                            fslot,
                                            0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
                                        ),
                                        and(mload(mc), mask)
                                    )
                                )
                                for {
                                    mc := add(mc, 0x20)
                                    sc := add(sc, 1)
                                } lt(mc, end) {
                                    sc := add(sc, 1)
                                    mc := add(mc, 0x20)
                                } {
                                    sstore(sc, mload(mc))
                                }
                                mask := exp(0x100, sub(mc, end))
                                sstore(sc, mul(div(mload(mc), mask), mask))
                            }
                            default {
                                // get the keccak hash to get the contents of the array
                                mstore(0x0, _preBytes.slot)
                                // Start copying to the last used word of the stored array.
                                let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                                // save new length
                                sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                                // Copy over the first `submod` bytes of the new data as in
                                // case 1 above.
                                let slengthmod := mod(slength, 32)
                                let mlengthmod := mod(mlength, 32)
                                let submod := sub(32, slengthmod)
                                let mc := add(_postBytes, submod)
                                let end := add(_postBytes, mlength)
                                let mask := sub(exp(0x100, submod), 1)
                                sstore(sc, add(sload(sc), and(mload(mc), mask)))
                                for {
                                    sc := add(sc, 1)
                                    mc := add(mc, 0x20)
                                } lt(mc, end) {
                                    sc := add(sc, 1)
                                    mc := add(mc, 0x20)
                                } {
                                    sstore(sc, mload(mc))
                                }
                                mask := exp(0x100, sub(mc, end))
                                sstore(sc, mul(div(mload(mc), mask), mask))
                            }
                        }
                    }
                    function slice(
                        bytes memory _bytes,
                        uint256 _start,
                        uint256 _length
                    )
                        internal
                        pure
                        returns (bytes memory)
                    {
                        require(_length + 31 >= _length, "slice_overflow");
                        require(_bytes.length >= _start + _length, "slice_outOfBounds");
                        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) {
                        require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
                        address tempAddress;
                        assembly {
                            tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
                        }
                        return tempAddress;
                    }
                    function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
                        require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
                        uint8 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x1), _start))
                        }
                        return tempUint;
                    }
                    function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
                        require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
                        uint16 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x2), _start))
                        }
                        return tempUint;
                    }
                    function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
                        require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
                        uint32 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x4), _start))
                        }
                        return tempUint;
                    }
                    function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
                        require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
                        uint64 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x8), _start))
                        }
                        return tempUint;
                    }
                    function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
                        require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
                        uint96 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0xc), _start))
                        }
                        return tempUint;
                    }
                    function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
                        require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
                        uint128 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x10), _start))
                        }
                        return tempUint;
                    }
                    function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
                        require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
                        uint256 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x20), _start))
                        }
                        return tempUint;
                    }
                    function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
                        require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
                        bytes32 tempBytes32;
                        assembly {
                            tempBytes32 := mload(add(add(_bytes, 0x20), _start))
                        }
                        return tempBytes32;
                    }
                    function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
                        bool success = true;
                        assembly {
                            let length := mload(_preBytes)
                            // if lengths don't match the arrays are not equal
                            switch eq(length, mload(_postBytes))
                            case 1 {
                                // cb is a circuit breaker in the for loop since there's
                                //  no said feature for inline assembly loops
                                // cb = 1 - don't breaker
                                // cb = 0 - break
                                let cb := 1
                                let mc := add(_preBytes, 0x20)
                                let end := add(mc, length)
                                for {
                                    let cc := add(_postBytes, 0x20)
                                // the next line is the loop condition:
                                // while(uint256(mc < end) + cb == 2)
                                } eq(add(lt(mc, end), cb), 2) {
                                    mc := add(mc, 0x20)
                                    cc := add(cc, 0x20)
                                } {
                                    // if any of these checks fails then arrays are not equal
                                    if iszero(eq(mload(mc), mload(cc))) {
                                        // unsuccess:
                                        success := 0
                                        cb := 0
                                    }
                                }
                            }
                            default {
                                // unsuccess:
                                success := 0
                            }
                        }
                        return success;
                    }
                    function equalStorage(
                        bytes storage _preBytes,
                        bytes memory _postBytes
                    )
                        internal
                        view
                        returns (bool)
                    {
                        bool success = true;
                        assembly {
                            // we know _preBytes_offset is 0
                            let fslot := sload(_preBytes.slot)
                            // Decode the length of the stored array like in concatStorage().
                            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                            let mlength := mload(_postBytes)
                            // if lengths don't match the arrays are not equal
                            switch eq(slength, mlength)
                            case 1 {
                                // slength can contain both the length and contents of the array
                                // if length < 32 bytes so let's prepare for that
                                // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                                if iszero(iszero(slength)) {
                                    switch lt(slength, 32)
                                    case 1 {
                                        // blank the last byte which is the length
                                        fslot := mul(div(fslot, 0x100), 0x100)
                                        if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
                                            // unsuccess:
                                            success := 0
                                        }
                                    }
                                    default {
                                        // cb is a circuit breaker in the for loop since there's
                                        //  no said feature for inline assembly loops
                                        // cb = 1 - don't breaker
                                        // cb = 0 - break
                                        let cb := 1
                                        // get the keccak hash to get the contents of the array
                                        mstore(0x0, _preBytes.slot)
                                        let sc := keccak256(0x0, 0x20)
                                        let mc := add(_postBytes, 0x20)
                                        let end := add(mc, mlength)
                                        // the next line is the loop condition:
                                        // while(uint256(mc < end) + cb == 2)
                                        for {} eq(add(lt(mc, end), cb), 2) {
                                            sc := add(sc, 1)
                                            mc := add(mc, 0x20)
                                        } {
                                            if iszero(eq(sload(sc), mload(mc))) {
                                                // unsuccess:
                                                success := 0
                                                cb := 0
                                            }
                                        }
                                    }
                                }
                            }
                            default {
                                // unsuccess:
                                success := 0
                            }
                        }
                        return success;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
                import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
                import "./libs/BytesLib.sol";
                contract MayanForwarder2 {
                \tusing SafeERC20 for IERC20;
                \tusing BytesLib for bytes;
                \tevent SwapAndForwarded(uint256 amount);
                \taddress public guardian;
                \taddress public nextGuardian;
                \tmapping(address => bool) public swapProtocols;
                \tmapping(address => bool) public mayanProtocols;
                \tevent ForwardedEth(address mayanProtocol, bytes protocolData);
                \tevent ForwardedERC20(address token, uint256 amount, address mayanProtocol, bytes protocolData);
                \tevent SwapAndForwardedEth(uint256 amountIn, address swapProtocol, address middleToken, uint256 middleAmount, address mayanProtocol, bytes mayanData);
                \tevent SwapAndForwardedERC20(address tokenIn, uint256 amountIn, address swapProtocol, address middleToken, uint256 middleAmount, address mayanProtocol, bytes mayanData);
                \terror UnsupportedProtocol();
                \tstruct PermitParams {
                \t\tuint256 value;
                \t\tuint256 deadline;
                \t\tuint8 v;
                \t\tbytes32 r;
                \t\tbytes32 s;
                \t}
                \tconstructor(address _guardian, address[] memory _swapProtocols, address[] memory _mayanProtocols) {
                \t\tguardian = _guardian;
                \t\tfor (uint256 i = 0; i < _swapProtocols.length; i++) {
                \t\t\tswapProtocols[_swapProtocols[i]] = true;
                \t\t}
                \t\tfor (uint256 i = 0; i < _mayanProtocols.length; i++) {
                \t\t\tmayanProtocols[_mayanProtocols[i]] = true;
                \t\t}
                \t}
                \tfunction forwardEth(
                \t\taddress mayanProtocol,
                \t\tbytes calldata protocolData
                \t) external payable {
                \t\tif (!mayanProtocols[mayanProtocol]) {
                \t\t\trevert UnsupportedProtocol();
                \t\t}
                \t\t(bool success, ) = mayanProtocol.call{value: msg.value}(protocolData);
                \t\trequire(success, "mayan protocol call failed");
                \t\temit ForwardedEth(mayanProtocol, protocolData);
                \t}
                \t
                \tfunction forwardERC20(
                \t\taddress tokenIn,
                \t\tuint256 amountIn,
                \t\tPermitParams calldata permitParams,
                \t\taddress mayanProtocol,
                \t\tbytes calldata protocolData
                \t\t) external payable {
                \t\tif (!mayanProtocols[mayanProtocol]) {
                \t\t\trevert UnsupportedProtocol();
                \t\t}
                \t\tpullTokenIn(tokenIn, amountIn, permitParams);
                \t\tmaxApproveIfNeeded(tokenIn, mayanProtocol, amountIn);
                \t\t(bool success, ) = mayanProtocol.call{value: msg.value}(protocolData);
                \t\trequire(success, "mayan protocol call failed");
                \t\temit ForwardedERC20(tokenIn, amountIn, mayanProtocol, protocolData);
                \t}
                \tfunction swapAndForwardEth(
                \t\tuint256 amountIn,
                \t\taddress swapProtocol,
                \t\tbytes calldata swapData,
                \t\taddress middleToken,
                \t\tuint256 minMiddleAmount,
                \t\taddress mayanProtocol,
                \t\tbytes calldata mayanData
                \t) external payable {
                \t\tif (!swapProtocols[swapProtocol] || !mayanProtocols[mayanProtocol]) {
                \t\t\trevert UnsupportedProtocol();
                \t\t}
                \t\trequire(middleToken != address(0), "middleToken cannot be zero address");
                \t\trequire(msg.value >= amountIn, "insufficient amountIn");
                \t\tuint256 middleAmount = IERC20(middleToken).balanceOf(address(this));
                \t\t(bool success, ) = swapProtocol.call{value: amountIn}(swapData);
                \t\trequire(success, "swap call failed");
                \t\tmiddleAmount = IERC20(middleToken).balanceOf(address(this)) - middleAmount;
                \t\trequire(middleAmount >= minMiddleAmount, "insufficient middle token");
                \t\tmaxApproveIfNeeded(middleToken, mayanProtocol, middleAmount);
                \t\tbytes memory modifiedData = replaceMiddleAmount(mayanData, middleAmount);
                \t\t(success, ) = mayanProtocol.call{value: msg.value - amountIn}(modifiedData);
                \t\trequire(success, "mayan protocol call failed");
                \t\temit SwapAndForwardedEth(amountIn, swapProtocol, middleToken, middleAmount, mayanProtocol, mayanData);
                \t}
                \tfunction swapAndForwardERC20(
                \t\taddress tokenIn,
                \t\tuint256 amountIn,
                \t\tPermitParams calldata permitParams,
                \t\taddress swapProtocol,
                \t\tbytes calldata swapData,
                \t\taddress middleToken,
                \t\tuint256 minMiddleAmount,
                \t\taddress mayanProtocol,
                \t\tbytes calldata mayanData
                \t) external payable {
                \t\tif (!swapProtocols[swapProtocol] || !mayanProtocols[mayanProtocol]) {
                \t\t\trevert UnsupportedProtocol();
                \t\t}
                \t\trequire(tokenIn != middleToken, "tokenIn and tokenOut must be different");
                \t\tuint256 amountBefore = IERC20(tokenIn).balanceOf(address(this));
                \t\tpullTokenIn(tokenIn, amountIn, permitParams);
                \t\tuint256 middleAmount;
                \t\tif (middleToken != address(0)) {
                \t\t\tmiddleAmount = IERC20(middleToken).balanceOf(address(this));
                \t\t} else {
                \t\t\tmiddleAmount = address(this).balance;
                \t\t}
                \t\tmaxApproveIfNeeded(tokenIn, swapProtocol, amountIn);
                \t\t(bool success, ) = swapProtocol.call{value: 0}(swapData);
                \t\trequire(success, "swap protocol call failed");
                \t\tif (middleToken != address(0)) {
                \t\t\tmiddleAmount = IERC20(middleToken).balanceOf(address(this)) - middleAmount;
                \t\t} else {
                \t\t\tmiddleAmount = address(this).balance - middleAmount;
                \t\t}
                \t\trequire(middleAmount >= minMiddleAmount, "insufficient middle token");
                \t\tuint256 val = msg.value;
                \t\tif (middleToken == address(0)) {
                \t\t\tval += middleAmount;
                \t\t} else {
                \t\t\tmaxApproveIfNeeded(middleToken, mayanProtocol, middleAmount);
                \t\t}
                \t\t(success, ) = mayanProtocol.call{value: val}(middleToken == address(0) ? mayanData : replaceMiddleAmount(mayanData, middleAmount));
                \t\trequire(success, "mayan protocol call failed");
                \t\ttransferBackRemaining(tokenIn, amountBefore);
                \t\temit SwapAndForwardedERC20(tokenIn, amountIn, swapProtocol, middleToken, middleAmount, mayanProtocol, mayanData);
                \t}
                \tfunction replaceMiddleAmount(bytes calldata mayanData, uint256 middleAmount) internal pure returns(bytes memory) {
                \t\trequire(mayanData.length >= 68, "Mayan data too short");
                \t\tbytes memory modifiedData = new bytes(mayanData.length);
                \t\t// Copy the function selector and token in
                \t\tfor (uint i = 0; i < 36; i++) {
                \t\t\tmodifiedData[i] = mayanData[i];
                \t\t}
                \t\t// Encode the amount and place it into the modified call data
                \t\t// Starting from byte 36 to byte 67 (32 bytes for uint256)
                \t\tbytes memory encodedAmount = abi.encode(middleAmount);
                \t\tfor (uint i = 0; i < 32; i++) {
                \t\t\tmodifiedData[i + 36] = encodedAmount[i];
                \t\t}
                \t\t// Copy the rest of the original data after the first argument
                \t\tfor (uint i = 68; i < mayanData.length; i++) {
                \t\t\tmodifiedData[i] = mayanData[i];
                \t\t}
                \t\treturn modifiedData;
                \t}
                \tfunction maxApproveIfNeeded(address tokenAddr, address spender, uint256 amount) internal {
                \t\tIERC20 token = IERC20(tokenAddr);
                \t\tuint256 currentAllowance = token.allowance(address(this), spender);
                \t\tif (currentAllowance < amount) {
                \t\t\ttoken.safeApprove(spender, 0);
                \t\t\ttoken.safeApprove(spender, type(uint256).max);
                \t\t}
                \t}
                \tfunction execPermit(
                \t\taddress token,
                \t\taddress owner,
                \t\tPermitParams calldata permitParams
                \t) internal {
                \t\tIERC20Permit(token).permit(
                \t\t\towner,
                \t\t\taddress(this),
                \t\t\tpermitParams.value,
                \t\t\tpermitParams.deadline,
                \t\t\tpermitParams.v,
                \t\t\tpermitParams.r,
                \t\t\tpermitParams.s
                \t\t);
                \t}
                \tfunction pullTokenIn(
                \t\taddress tokenIn,
                \t\tuint256 amountIn,
                \t\tPermitParams calldata permitParams
                \t) internal {
                \t\tuint256 allowance = IERC20(tokenIn).allowance(msg.sender, address(this));
                \t\tif (allowance < amountIn) {
                \t\t\texecPermit(tokenIn, msg.sender, permitParams);
                \t\t}
                \t\tIERC20(tokenIn).safeTransferFrom(msg.sender, address(this), amountIn);
                \t}
                \tfunction transferBackRemaining(address token, uint256 amountBefore) internal {
                \t\tuint256 remaining = IERC20(token).balanceOf(address(this));
                \t\tif (remaining > amountBefore) {
                \t\t\tIERC20(token).safeTransfer(msg.sender, remaining - amountBefore);
                \t\t}
                \t}
                \tfunction rescueToken(address token, uint256 amount, address to) public {
                \t\trequire(msg.sender == guardian, 'only guardian');
                \t\tIERC20(token).safeTransfer(to, amount);
                \t}
                \tfunction rescueEth(uint256 amount, address payable to) public {
                \t\trequire(msg.sender == guardian, 'only guardian');
                \t\trequire(to != address(0), 'transfer to the zero address');
                \t\t(bool success, ) = payable(to).call{value: amount}('');
                \t\trequire(success, 'payment failed');
                \t}
                \tfunction changeGuardian(address newGuardian) public {
                \t\trequire(msg.sender == guardian, 'only guardian');
                \t\tnextGuardian = newGuardian;
                \t}
                \tfunction claimGuardian() public {
                \t\trequire(msg.sender == nextGuardian, 'only next guardian');
                \t\tguardian = nextGuardian;
                \t}
                \tfunction setSwapProtocol(address swapProtocol, bool enabled) public {
                \t\trequire(msg.sender == guardian, 'only guardian');
                \t\tswapProtocols[swapProtocol] = enabled;
                \t}
                \tfunction setMayanProtocol(address mayanProtocol, bool enabled) public {
                \t\trequire(msg.sender == guardian, 'only guardian');
                \t\tmayanProtocols[mayanProtocol] = enabled;
                \t}
                \treceive() external payable {}
                }

                File 4 of 5: MayanFacet
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity ^0.8.17;
                import { ILiFi } from "../Interfaces/ILiFi.sol";
                import { LibAsset, IERC20 } from "../Libraries/LibAsset.sol";
                import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
                import { LibSwap } from "../Libraries/LibSwap.sol";
                import { ReentrancyGuard } from "../Helpers/ReentrancyGuard.sol";
                import { SwapperV2 } from "../Helpers/SwapperV2.sol";
                import { Validatable } from "../Helpers/Validatable.sol";
                import { IMayan } from "../Interfaces/IMayan.sol";
                import { LiFiData } from "../Helpers/LiFiData.sol";
                import { InvalidConfig, InvalidNonEVMReceiver } from "../Errors/GenericErrors.sol";
                /// @title Mayan Facet
                /// @author LI.FI (https://li.fi)
                /// @notice Provides functionality for bridging through Mayan Bridge
                /// @custom:version 1.2.2
                contract MayanFacet is
                    ILiFi,
                    ReentrancyGuard,
                    SwapperV2,
                    Validatable,
                    LiFiData
                {
                    /// Storage ///
                    bytes32 internal constant NAMESPACE = keccak256("com.lifi.facets.mayan");
                    IMayan public immutable MAYAN;
                    /// @dev Mayan specific bridge data
                    /// @param nonEVMReceiver The address of the non-EVM receiver if applicable
                    /// @param mayanProtocol The address of the Mayan protocol final contract
                    /// @param protocolData The protocol data for the Mayan protocol
                    struct MayanData {
                        bytes32 nonEVMReceiver;
                        address mayanProtocol;
                        bytes protocolData;
                    }
                    /// Errors ///
                    error InvalidReceiver(address expected, address actual);
                    error ProtocolDataTooShort();
                    /// Constructor ///
                    /// @notice Constructor for the contract.
                    constructor(IMayan _mayan) {
                        if (address(_mayan) == address(0)) revert InvalidConfig();
                        MAYAN = _mayan;
                    }
                    /// External Methods ///
                    /// @notice Bridges tokens via Mayan
                    /// @param _bridgeData The core information needed for bridging
                    /// @param _mayanData Data specific to Mayan
                    function startBridgeTokensViaMayan(
                        ILiFi.BridgeData memory _bridgeData,
                        MayanData calldata _mayanData
                    )
                        external
                        payable
                        nonReentrant
                        refundExcessNative(payable(msg.sender))
                        validateBridgeData(_bridgeData)
                        doesNotContainSourceSwaps(_bridgeData)
                        doesNotContainDestinationCalls(_bridgeData)
                    {
                        LibAsset.depositAsset(
                            _bridgeData.sendingAssetId,
                            _bridgeData.minAmount
                        );
                        if (LibAsset.isNativeAsset(_bridgeData.sendingAssetId)) {
                            // Normalize the amount to 8 decimals
                            _bridgeData.minAmount = _normalizeAmount(
                                _bridgeData.minAmount,
                                18
                            );
                        }
                        _startBridge(_bridgeData, _mayanData);
                    }
                    /// @notice Performs a swap before bridging via Mayan
                    /// @param _bridgeData The core information needed for bridging
                    /// @param _swapData An array of swap related data for performing swaps before bridging
                    /// @param _mayanData Data specific to Mayan
                    function swapAndStartBridgeTokensViaMayan(
                        ILiFi.BridgeData memory _bridgeData,
                        LibSwap.SwapData[] calldata _swapData,
                        MayanData memory _mayanData
                    )
                        external
                        payable
                        nonReentrant
                        refundExcessNative(payable(msg.sender))
                        containsSourceSwaps(_bridgeData)
                        doesNotContainDestinationCalls(_bridgeData)
                        validateBridgeData(_bridgeData)
                    {
                        _bridgeData.minAmount = _depositAndSwap(
                            _bridgeData.transactionId,
                            _bridgeData.minAmount,
                            _swapData,
                            payable(msg.sender)
                        );
                        uint256 decimals;
                        bool isNative = LibAsset.isNativeAsset(_bridgeData.sendingAssetId);
                        decimals = isNative
                            ? 18
                            : ERC20(_bridgeData.sendingAssetId).decimals();
                        // Normalize the amount to 8 decimals
                        _bridgeData.minAmount = _normalizeAmount(
                            _bridgeData.minAmount,
                            uint8(decimals)
                        );
                        // Native values are not passed as calldata
                        if (!isNative) {
                            // Update the protocol data with the new input amount
                            _mayanData.protocolData = _replaceInputAmount(
                                _mayanData.protocolData,
                                _bridgeData.minAmount
                            );
                        }
                        _startBridge(_bridgeData, _mayanData);
                    }
                    /// Internal Methods ///
                    /// @dev Contains the business logic for the bridge via Mayan
                    /// @param _bridgeData The core information needed for bridging
                    /// @param _mayanData Data specific to Mayan
                    function _startBridge(
                        ILiFi.BridgeData memory _bridgeData,
                        MayanData memory _mayanData
                    ) internal {
                        // Validate receiver address
                        if (_bridgeData.receiver == NON_EVM_ADDRESS) {
                            if (_mayanData.nonEVMReceiver == bytes32(0)) {
                                revert InvalidNonEVMReceiver();
                            }
                            bytes32 receiver = _parseReceiver(_mayanData.protocolData);
                            if (_mayanData.nonEVMReceiver != receiver) {
                                revert InvalidNonEVMReceiver();
                            }
                        } else {
                            address receiver = address(
                                uint160(uint256(_parseReceiver(_mayanData.protocolData)))
                            );
                            if (_bridgeData.receiver != receiver) {
                                revert InvalidReceiver(_bridgeData.receiver, receiver);
                            }
                        }
                        IMayan.PermitParams memory emptyPermitParams;
                        if (!LibAsset.isNativeAsset(_bridgeData.sendingAssetId)) {
                            LibAsset.maxApproveERC20(
                                IERC20(_bridgeData.sendingAssetId),
                                address(MAYAN),
                                _bridgeData.minAmount
                            );
                            MAYAN.forwardERC20(
                                _bridgeData.sendingAssetId,
                                _bridgeData.minAmount,
                                emptyPermitParams,
                                _mayanData.mayanProtocol,
                                _mayanData.protocolData
                            );
                        } else {
                            MAYAN.forwardEth{ value: _bridgeData.minAmount }(
                                _mayanData.mayanProtocol,
                                _mayanData.protocolData
                            );
                        }
                        if (_bridgeData.receiver == NON_EVM_ADDRESS) {
                            emit BridgeToNonEVMChainBytes32(
                                _bridgeData.transactionId,
                                _bridgeData.destinationChainId,
                                _mayanData.nonEVMReceiver
                            );
                        }
                        emit LiFiTransferStarted(_bridgeData);
                    }
                    // @dev Parses the receiver address from the protocol data
                    // @param protocolData The protocol data for the Mayan protocol
                    // @return receiver The receiver address
                    function _parseReceiver(
                        bytes memory protocolData
                    ) internal pure returns (bytes32 receiver) {
                        bytes4 selector;
                        assembly {
                            // Load the selector from the protocol data
                            selector := mload(add(protocolData, 0x20))
                            // Shift the selector to the right by 224 bits to match shape of literal in switch statement
                            let shiftedSelector := shr(224, selector)
                            switch shiftedSelector
                            // Note: [*bytes32*] = location of receiver address
                            case 0x94454a5d {
                                // 0x94454a5d bridgeWithFee(address,uint256,uint64,uint64,[*bytes32*],(uint32,bytes32,bytes32))
                                receiver := mload(add(protocolData, 0xa4)) // MayanCircle::bridgeWithFee()
                            }
                            case 0x32ad465f {
                                // 0x32ad465f bridgeWithLockedFee(address,uint256,uint64,uint256,(uint32,[*bytes32*],bytes32))
                                receiver := mload(add(protocolData, 0xc4)) // MayanCircle::bridgeWithLockedFee()
                            }
                            case 0xafd9b706 {
                                // 0xafd9b706 createOrder((address,uint256,uint64,[*bytes32*],uint16,bytes32,uint64,uint64,uint64,bytes32,uint8),(uint32,bytes32,bytes32))
                                receiver := mload(add(protocolData, 0x84)) // MayanCircle::createOrder()
                            }
                            case 0x6111ad25 {
                                // 0x6111ad25 swap((uint64,uint64,uint64),(bytes32,uint16,bytes32,[*bytes32*],uint16,bytes32,bytes32),bytes32,uint16,(uint256,uint64,uint64,bool,uint64,bytes),address,uint256)
                                receiver := mload(add(protocolData, 0xe4)) // MayanSwap::swap()
                            }
                            case 0x1eb1cff0 {
                                // 0x1eb1cff0 wrapAndSwapETH((uint64,uint64,uint64),(bytes32,uint16,bytes32,[*bytes32*],uint16,bytes32,bytes32),bytes32,uint16,(uint256,uint64,uint64,bool,uint64,bytes))
                                receiver := mload(add(protocolData, 0xe4)) // MayanSwap::wrapAndSwapETH()
                            }
                            case 0xb866e173 {
                                // 0xb866e173 createOrderWithEth((bytes32,bytes32,uint64,uint64,uint64,uint64,uint64,[*bytes32*],uint16,bytes32,uint8,uint8,bytes32))
                                receiver := mload(add(protocolData, 0x104)) // MayanSwift::createOrderWithEth()
                            }
                            case 0x8e8d142b {
                                // 0x8e8d142b createOrderWithToken(address,uint256,(bytes32,bytes32,uint64,uint64,uint64,uint64,uint64,[*bytes32*],uint16,bytes32,uint8,uint8,bytes32))
                                receiver := mload(add(protocolData, 0x144)) // MayanSwift::createOrderWithToken()
                            }
                            case 0x1c59b7fc {
                                // 0x1c59b7fc MayanCircle::createOrder((address,uint256,uint64,bytes32,uint16,bytes32,uint64,uint64,uint64,bytes32,uint8))
                                receiver := mload(add(protocolData, 0x84))
                            }
                            case 0x9be95bb4 {
                                // 0x9be95bb4 MayanCircle::bridgeWithLockedFee(address,uint256,uint64,uint256,uint32,bytes32)
                                receiver := mload(add(protocolData, 0xc4))
                            }
                            case 0x2072197f {
                                // 0x2072197f MayanCircle::bridgeWithFee(address,uint256,uint64,uint64,bytes32,uint32,uint8,bytes)
                                receiver := mload(add(protocolData, 0xa4))
                            }
                            case 0xf58b6de8 {
                                // 0xf58b6de8 FastMCTP::bridge(address,uint256,uint64,uint256,uint64,[*bytes32*],uint32,bytes32,uint8,uint8,uint32,bytes)
                                receiver := mload(add(protocolData, 0xc4))
                            }
                            case 0x2337e236 {
                                // 0x2337e236 FastMCTP::createOrder(address,uint256,uint256,uint32,uint32,(bytes32,[*bytes32*],uint64,uint64,uint64,uint64,uint64,bytes32,uint16,bytes32,uint8,uint8,bytes32))
                                receiver := mload(add(protocolData, 0xe4))
                            }
                            case 0xe27dce37 {
                                // 0xe27dce37 HCDepositInitiator::deposit(address,uint256,address,uint64,uint256,uint256,(uint64,([*address*],uint256,uint256,(bytes32,bytes32,uint8))))
                                // @notice Important behavior regarding permits and receivers in Mayan bridge for Hypercore:
                                // 1. The DepositPayload struct (tuple) only contains permit data, with no separate receiver field
                                // 2. The permit signer in DepositPayload struct (not the trader (3rd argument)) is who receives the bridged funds
                                // 3. While technically possible to bridge to a different receiver, it requires having that receiver's permit
                                //
                                // Implementation note:
                                // Due to these constraints, the sender must act as the receiver
                                // since they need to provide their own permit. This limitation is handled at the backend level
                                // by disabling the option to specify a different receiver.
                                //
                                receiver := mload(add(protocolData, 0xe4))
                            }
                            case 0x4d1ed73b {
                                // 0x4d1ed73b HCDepositInitiator::fastDeposit(address,uint256,address,uint256,uint64,bytes32,uint8,uint32,uint256,(uint64,([*address*],uint256,uint256,(bytes32,bytes32,uint8))))
                                // @notice Important behavior regarding permits and receivers in Mayan bridge for Hypercore:
                                // 1. The DepositPayload struct (tuple) only contains permit data, with no separate receiver field
                                // 2. The permit signer in DepositPayload struct (not the trader (3rd argument)) is who receives the bridged funds
                                // 3. While technically possible to bridge to a different receiver, it requires having that receiver's permit
                                //
                                // Implementation note:
                                // Due to these constraints, the sender must act as the receiver
                                // since they need to provide their own permit. This limitation is handled at the backend level
                                // by disabling the option to specify a different receiver.
                                //
                                receiver := mload(add(protocolData, 0x164))
                            }
                            default {
                                receiver := 0x0
                            }
                        }
                    }
                    // @dev Normalizes the amount to 8 decimals
                    // @param amount The amount to normalize
                    // @param decimals The number of decimals in the asset
                    function _normalizeAmount(
                        uint256 amount,
                        uint8 decimals
                    ) internal pure returns (uint256) {
                        if (decimals > 8) {
                            amount /= 10 ** (decimals - 8);
                            amount *= 10 ** (decimals - 8);
                        }
                        return amount;
                    }
                    // @dev Replaces the input amount in the protocol data
                    // @param protocolData The protocol data for the Mayan protocol
                    // @param inputAmount The new input amount
                    // @return modifiedData The modified protocol data
                    function _replaceInputAmount(
                        bytes memory protocolData,
                        uint256 inputAmount
                    ) internal pure returns (bytes memory) {
                        if (protocolData.length < 68) {
                            revert ProtocolDataTooShort();
                        }
                        bytes memory modifiedData = new bytes(protocolData.length);
                        bytes4 functionSelector = bytes4(protocolData[0]) |
                            (bytes4(protocolData[1]) >> 8) |
                            (bytes4(protocolData[2]) >> 16) |
                            (bytes4(protocolData[3]) >> 24);
                        uint256 amountIndex;
                        // Only the wh swap method has the amount as last argument
                        bytes4 swapSelector = 0x6111ad25;
                        if (functionSelector == swapSelector) {
                            amountIndex = protocolData.length - 256;
                        } else {
                            amountIndex = 36;
                        }
                        // Copy the function selector and params before amount in
                        for (uint256 i = 0; i < amountIndex; i++) {
                            modifiedData[i] = protocolData[i];
                        }
                        // Encode the amount and place it into the modified call data
                        bytes memory encodedAmount = abi.encode(inputAmount);
                        for (uint256 i = 0; i < 32; i++) {
                            modifiedData[i + amountIndex] = encodedAmount[i];
                        }
                        // Copy the rest of the original data after the input argument
                        for (uint256 i = amountIndex + 32; i < protocolData.length; i++) {
                            modifiedData[i] = protocolData[i];
                        }
                        return modifiedData;
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity ^0.8.17;
                /// @title ILiFi
                /// @author LI.FI (https://li.fi)
                /// @custom:version 1.0.1
                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
                    );
                    // this event is emitted when a bridge transction is initiated to a non-EVM chain
                    event BridgeToNonEVMChain(
                        bytes32 indexed transactionId,
                        uint256 indexed destinationChainId,
                        bytes receiver
                    );
                    event BridgeToNonEVMChainBytes32(
                        bytes32 indexed transactionId,
                        uint256 indexed destinationChainId,
                        bytes32 receiver
                    );
                    // 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: UNLICENSED
                pragma solidity ^0.8.17;
                import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                import { LibSwap } from "./LibSwap.sol";
                import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol";
                // solhint-disable-next-line max-line-length
                import { InvalidReceiver, NullAddrIsNotAValidSpender, InvalidAmount, NullAddrIsNotAnERC20Token } from "../Errors/GenericErrors.sol";
                /// @title LibAsset
                /// @custom:version 2.1.1
                /// @author LI.FI (https://li.fi)
                /// @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 {
                    using SafeTransferLib for address;
                    using SafeTransferLib for address payable;
                    /// @dev All native assets use the empty address for their asset id
                    ///      by convention
                    address internal constant NULL_ADDRESS = address(0);
                    /// @dev EIP-7702 delegation designator prefix for Account Abstraction
                    bytes3 internal constant DELEGATION_DESIGNATOR = 0xef0100;
                    /// @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 (returns 0 if assetId does not exist)
                    function getOwnBalance(address assetId) internal view returns (uint256) {
                        return
                            isNativeAsset(assetId)
                                ? address(this).balance
                                : assetId.balanceOf(address(this));
                    }
                    /// @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 {
                        if (isNativeAsset(assetId)) {
                            transferNativeAsset(recipient, amount);
                        } else {
                            transferERC20(assetId, recipient, amount);
                        }
                    }
                    /// @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 {
                        // make sure a meaningful receiver address was provided
                        if (recipient == NULL_ADDRESS) revert InvalidReceiver();
                        // transfer native asset (will revert if target reverts or contract has insufficient balance)
                        recipient.safeTransferETH(amount);
                    }
                    /// @notice Transfers tokens from the inheriting contract to a given recipient
                    /// @param assetId Token address to transfer
                    /// @param recipient Address to send tokens to
                    /// @param amount Amount to send to given recipient
                    function transferERC20(
                        address assetId,
                        address recipient,
                        uint256 amount
                    ) private {
                        // make sure a meaningful receiver address was provided
                        if (recipient == NULL_ADDRESS) {
                            revert InvalidReceiver();
                        }
                        // transfer ERC20 assets (will revert if target reverts or contract has insufficient balance)
                        assetId.safeTransfer(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 recipient Address of recipient/spender
                    /// @param amount Amount to transfer from owner to spender
                    function transferFromERC20(
                        address assetId,
                        address from,
                        address recipient,
                        uint256 amount
                    ) internal {
                        // check if native asset
                        if (isNativeAsset(assetId)) {
                            revert NullAddrIsNotAnERC20Token();
                        }
                        // make sure a meaningful receiver address was provided
                        if (recipient == NULL_ADDRESS) {
                            revert InvalidReceiver();
                        }
                        // transfer ERC20 assets (will revert if target reverts or contract has insufficient balance)
                        assetId.safeTransferFrom(from, recipient, amount);
                    }
                    /// @notice Pulls tokens from msg.sender
                    /// @param assetId Token address to transfer
                    /// @param amount Amount to transfer from owner
                    function depositAsset(address assetId, uint256 amount) internal {
                        // make sure a meaningful amount was provided
                        if (amount == 0) revert InvalidAmount();
                        // check if native asset
                        if (isNativeAsset(assetId)) {
                            // ensure msg.value is equal or greater than amount
                            if (msg.value < amount) revert InvalidAmount();
                        } else {
                            // transfer ERC20 assets (will revert if target reverts or contract has insufficient balance)
                            assetId.safeTransferFrom(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 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 allowance amount required for current transaction
                    function maxApproveERC20(
                        IERC20 assetId,
                        address spender,
                        uint256 amount
                    ) internal {
                        approveERC20(assetId, spender, amount, type(uint256).max);
                    }
                    /// @notice If the current allowance is insufficient, the allowance for a given spender
                    ///         is set to the amount provided
                    /// @param assetId Token address to transfer
                    /// @param spender Address to give spend approval to
                    /// @param requiredAllowance Allowance required for current transaction
                    /// @param setAllowanceTo The amount the allowance should be set to if current allowance is insufficient
                    function approveERC20(
                        IERC20 assetId,
                        address spender,
                        uint256 requiredAllowance,
                        uint256 setAllowanceTo
                    ) internal {
                        if (isNativeAsset(address(assetId))) {
                            return;
                        }
                        // make sure a meaningful spender address was provided
                        if (spender == NULL_ADDRESS) {
                            revert NullAddrIsNotAValidSpender();
                        }
                        // check if allowance is sufficient, otherwise set allowance to provided amount
                        // If the initial attempt to approve fails, attempts to reset the approved amount to zero,
                        // then retries the approval again (some tokens, e.g. USDT, requires this).
                        // Reverts upon failure
                        if (assetId.allowance(address(this), spender) < requiredAllowance) {
                            address(assetId).safeApproveWithRetry(spender, setAllowanceTo);
                        }
                    }
                    /// @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 == NULL_ADDRESS;
                    }
                    /// @notice Checks if the given address is a contract
                    ///         Returns true for any account with runtime code (excluding EIP-7702 accounts).
                    ///         For EIP-7702 accounts, checks if code size is exactly 23 bytes (delegation format).
                    ///         Limitations:
                    ///         - Cannot distinguish between EOA and self-destructed contract
                    /// @param account The address to be checked
                    function isContract(address account) internal view returns (bool) {
                        uint256 size;
                        assembly {
                            size := extcodesize(account)
                        }
                        // Return true only for regular contracts (size > 23)
                        // EIP-7702 delegated accounts (size == 23) are still EOAs, not contracts
                        return size > 23;
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
                pragma solidity ^0.8.0;
                import "./IERC20.sol";
                import "./extensions/IERC20Metadata.sol";
                import "../../utils/Context.sol";
                /**
                 * @dev Implementation of the {IERC20} interface.
                 *
                 * This implementation is agnostic to the way tokens are created. This means
                 * that a supply mechanism has to be added in a derived contract using {_mint}.
                 * For a generic mechanism see {ERC20PresetMinterPauser}.
                 *
                 * TIP: For a detailed writeup see our guide
                 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
                 * to implement supply mechanisms].
                 *
                 * The default value of {decimals} is 18. To change this, you should override
                 * this function so it returns a different value.
                 *
                 * We have followed general OpenZeppelin Contracts guidelines: functions revert
                 * instead returning `false` on failure. This behavior is nonetheless
                 * conventional and does not conflict with the expectations of ERC20
                 * applications.
                 *
                 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
                 * This allows applications to reconstruct the allowance for all accounts just
                 * by listening to said events. Other implementations of the EIP may not emit
                 * these events, as it isn't required by the specification.
                 *
                 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
                 * functions have been added to mitigate the well-known issues around setting
                 * allowances. See {IERC20-approve}.
                 */
                contract ERC20 is Context, IERC20, IERC20Metadata {
                    mapping(address => uint256) private _balances;
                    mapping(address => mapping(address => uint256)) private _allowances;
                    uint256 private _totalSupply;
                    string private _name;
                    string private _symbol;
                    /**
                     * @dev Sets the values for {name} and {symbol}.
                     *
                     * All two of these values are immutable: they can only be set once during
                     * construction.
                     */
                    constructor(string memory name_, string memory symbol_) {
                        _name = name_;
                        _symbol = symbol_;
                    }
                    /**
                     * @dev Returns the name of the token.
                     */
                    function name() public view virtual override returns (string memory) {
                        return _name;
                    }
                    /**
                     * @dev Returns the symbol of the token, usually a shorter version of the
                     * name.
                     */
                    function symbol() public view virtual override returns (string memory) {
                        return _symbol;
                    }
                    /**
                     * @dev Returns the number of decimals used to get its user representation.
                     * For example, if `decimals` equals `2`, a balance of `505` tokens should
                     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
                     *
                     * Tokens usually opt for a value of 18, imitating the relationship between
                     * Ether and Wei. This is the default value returned by this function, unless
                     * it's overridden.
                     *
                     * NOTE: This information is only used for _display_ purposes: it in
                     * no way affects any of the arithmetic of the contract, including
                     * {IERC20-balanceOf} and {IERC20-transfer}.
                     */
                    function decimals() public view virtual override returns (uint8) {
                        return 18;
                    }
                    /**
                     * @dev See {IERC20-totalSupply}.
                     */
                    function totalSupply() public view virtual override returns (uint256) {
                        return _totalSupply;
                    }
                    /**
                     * @dev See {IERC20-balanceOf}.
                     */
                    function balanceOf(address account) public view virtual override returns (uint256) {
                        return _balances[account];
                    }
                    /**
                     * @dev See {IERC20-transfer}.
                     *
                     * Requirements:
                     *
                     * - `to` cannot be the zero address.
                     * - the caller must have a balance of at least `amount`.
                     */
                    function transfer(address to, uint256 amount) public virtual override returns (bool) {
                        address owner = _msgSender();
                        _transfer(owner, to, amount);
                        return true;
                    }
                    /**
                     * @dev See {IERC20-allowance}.
                     */
                    function allowance(address owner, address spender) public view virtual override returns (uint256) {
                        return _allowances[owner][spender];
                    }
                    /**
                     * @dev See {IERC20-approve}.
                     *
                     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
                     * `transferFrom`. This is semantically equivalent to an infinite approval.
                     *
                     * Requirements:
                     *
                     * - `spender` cannot be the zero address.
                     */
                    function approve(address spender, uint256 amount) public virtual override returns (bool) {
                        address owner = _msgSender();
                        _approve(owner, spender, amount);
                        return true;
                    }
                    /**
                     * @dev See {IERC20-transferFrom}.
                     *
                     * Emits an {Approval} event indicating the updated allowance. This is not
                     * required by the EIP. See the note at the beginning of {ERC20}.
                     *
                     * NOTE: Does not update the allowance if the current allowance
                     * is the maximum `uint256`.
                     *
                     * Requirements:
                     *
                     * - `from` and `to` cannot be the zero address.
                     * - `from` must have a balance of at least `amount`.
                     * - the caller must have allowance for ``from``'s tokens of at least
                     * `amount`.
                     */
                    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
                        address spender = _msgSender();
                        _spendAllowance(from, spender, amount);
                        _transfer(from, to, amount);
                        return true;
                    }
                    /**
                     * @dev Atomically increases the allowance granted to `spender` by the caller.
                     *
                     * This is an alternative to {approve} that can be used as a mitigation for
                     * problems described in {IERC20-approve}.
                     *
                     * Emits an {Approval} event indicating the updated allowance.
                     *
                     * Requirements:
                     *
                     * - `spender` cannot be the zero address.
                     */
                    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                        address owner = _msgSender();
                        _approve(owner, spender, allowance(owner, spender) + addedValue);
                        return true;
                    }
                    /**
                     * @dev Atomically decreases the allowance granted to `spender` by the caller.
                     *
                     * This is an alternative to {approve} that can be used as a mitigation for
                     * problems described in {IERC20-approve}.
                     *
                     * Emits an {Approval} event indicating the updated allowance.
                     *
                     * Requirements:
                     *
                     * - `spender` cannot be the zero address.
                     * - `spender` must have allowance for the caller of at least
                     * `subtractedValue`.
                     */
                    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                        address owner = _msgSender();
                        uint256 currentAllowance = allowance(owner, spender);
                        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
                        unchecked {
                            _approve(owner, spender, currentAllowance - subtractedValue);
                        }
                        return true;
                    }
                    /**
                     * @dev Moves `amount` of tokens from `from` to `to`.
                     *
                     * This internal function is equivalent to {transfer}, and can be used to
                     * e.g. implement automatic token fees, slashing mechanisms, etc.
                     *
                     * Emits a {Transfer} event.
                     *
                     * Requirements:
                     *
                     * - `from` cannot be the zero address.
                     * - `to` cannot be the zero address.
                     * - `from` must have a balance of at least `amount`.
                     */
                    function _transfer(address from, address to, uint256 amount) internal virtual {
                        require(from != address(0), "ERC20: transfer from the zero address");
                        require(to != address(0), "ERC20: transfer to the zero address");
                        _beforeTokenTransfer(from, to, amount);
                        uint256 fromBalance = _balances[from];
                        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
                        unchecked {
                            _balances[from] = fromBalance - amount;
                            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
                            // decrementing then incrementing.
                            _balances[to] += amount;
                        }
                        emit Transfer(from, to, amount);
                        _afterTokenTransfer(from, to, amount);
                    }
                    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
                     * the total supply.
                     *
                     * Emits a {Transfer} event with `from` set to the zero address.
                     *
                     * Requirements:
                     *
                     * - `account` cannot be the zero address.
                     */
                    function _mint(address account, uint256 amount) internal virtual {
                        require(account != address(0), "ERC20: mint to the zero address");
                        _beforeTokenTransfer(address(0), account, amount);
                        _totalSupply += amount;
                        unchecked {
                            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
                            _balances[account] += amount;
                        }
                        emit Transfer(address(0), account, amount);
                        _afterTokenTransfer(address(0), account, amount);
                    }
                    /**
                     * @dev Destroys `amount` tokens from `account`, reducing the
                     * total supply.
                     *
                     * Emits a {Transfer} event with `to` set to the zero address.
                     *
                     * Requirements:
                     *
                     * - `account` cannot be the zero address.
                     * - `account` must have at least `amount` tokens.
                     */
                    function _burn(address account, uint256 amount) internal virtual {
                        require(account != address(0), "ERC20: burn from the zero address");
                        _beforeTokenTransfer(account, address(0), amount);
                        uint256 accountBalance = _balances[account];
                        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
                        unchecked {
                            _balances[account] = accountBalance - amount;
                            // Overflow not possible: amount <= accountBalance <= totalSupply.
                            _totalSupply -= amount;
                        }
                        emit Transfer(account, address(0), amount);
                        _afterTokenTransfer(account, address(0), amount);
                    }
                    /**
                     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
                     *
                     * This internal function is equivalent to `approve`, and can be used to
                     * e.g. set automatic allowances for certain subsystems, etc.
                     *
                     * Emits an {Approval} event.
                     *
                     * Requirements:
                     *
                     * - `owner` cannot be the zero address.
                     * - `spender` cannot be the zero address.
                     */
                    function _approve(address owner, address spender, uint256 amount) internal virtual {
                        require(owner != address(0), "ERC20: approve from the zero address");
                        require(spender != address(0), "ERC20: approve to the zero address");
                        _allowances[owner][spender] = amount;
                        emit Approval(owner, spender, amount);
                    }
                    /**
                     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
                     *
                     * Does not update the allowance amount in case of infinite allowance.
                     * Revert if not enough allowance is available.
                     *
                     * Might emit an {Approval} event.
                     */
                    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
                        uint256 currentAllowance = allowance(owner, spender);
                        if (currentAllowance != type(uint256).max) {
                            require(currentAllowance >= amount, "ERC20: insufficient allowance");
                            unchecked {
                                _approve(owner, spender, currentAllowance - amount);
                            }
                        }
                    }
                    /**
                     * @dev Hook that is called before any transfer of tokens. This includes
                     * minting and burning.
                     *
                     * Calling conditions:
                     *
                     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                     * will be transferred to `to`.
                     * - when `from` is zero, `amount` tokens will be minted for `to`.
                     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
                     * - `from` and `to` are never both zero.
                     *
                     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                     */
                    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
                    /**
                     * @dev Hook that is called after any transfer of tokens. This includes
                     * minting and burning.
                     *
                     * Calling conditions:
                     *
                     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                     * has been transferred to `to`.
                     * - when `from` is zero, `amount` tokens have been minted for `to`.
                     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
                     * - `from` and `to` are never both zero.
                     *
                     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                     */
                    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity ^0.8.17;
                import { LibAsset } from "./LibAsset.sol";
                import { LibUtil } from "./LibUtil.sol";
                import { InvalidContract, NoSwapFromZeroBalance } from "../Errors/GenericErrors.sol";
                import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                /// @title LibSwap
                /// @custom:version 1.1.0
                /// @notice This library contains functionality to execute mostly swaps but also
                ///         other calls such as fee collection, token wrapping/unwrapping or
                ///         sending gas to destination chain
                library LibSwap {
                    /// @notice Struct containing all necessary data to execute a swap or generic call
                    /// @param callTo The address of the contract to call for executing the swap
                    /// @param approveTo The address that will receive token approval (can be different than callTo for some DEXs)
                    /// @param sendingAssetId The address of the token being sent
                    /// @param receivingAssetId The address of the token expected to be received
                    /// @param fromAmount The exact amount of the sending asset to be used in the call
                    /// @param callData Encoded function call data to be sent to the `callTo` contract
                    /// @param requiresDeposit A flag indicating whether the tokens must be deposited (pulled) before the call
                    struct SwapData {
                        address callTo;
                        address approveTo;
                        address sendingAssetId;
                        address receivingAssetId;
                        uint256 fromAmount;
                        bytes callData;
                        bool requiresDeposit;
                    }
                    /// @notice Emitted after a successful asset swap or related operation
                    /// @param transactionId    The unique identifier associated with the swap operation
                    /// @param dex              The address of the DEX or contract that handled the swap
                    /// @param fromAssetId      The address of the token that was sent
                    /// @param toAssetId        The address of the token that was received
                    /// @param fromAmount       The amount of `fromAssetId` sent
                    /// @param toAmount         The amount of `toAssetId` received
                    /// @param timestamp        The timestamp when the swap was executed
                    event AssetSwapped(
                        bytes32 transactionId,
                        address dex,
                        address fromAssetId,
                        address toAssetId,
                        uint256 fromAmount,
                        uint256 toAmount,
                        uint256 timestamp
                    );
                    function swap(bytes32 transactionId, SwapData calldata _swap) internal {
                        // make sure callTo is a contract
                        if (!LibAsset.isContract(_swap.callTo)) revert InvalidContract();
                        // make sure that fromAmount is not 0
                        uint256 fromAmount = _swap.fromAmount;
                        if (fromAmount == 0) revert NoSwapFromZeroBalance();
                        // determine how much native value to send with the swap call
                        uint256 nativeValue = LibAsset.isNativeAsset(_swap.sendingAssetId)
                            ? _swap.fromAmount
                            : 0;
                        // store initial balance (required for event emission)
                        uint256 initialReceivingAssetBalance = LibAsset.getOwnBalance(
                            _swap.receivingAssetId
                        );
                        // max approve (if ERC20)
                        if (nativeValue == 0) {
                            LibAsset.maxApproveERC20(
                                IERC20(_swap.sendingAssetId),
                                _swap.approveTo,
                                _swap.fromAmount
                            );
                        }
                        // we used to have a sending asset balance check here (initialSendingAssetBalance >= _swap.fromAmount)
                        // this check was removed to allow for more flexibility with rebasing/fee-taking tokens
                        // the general assumption is that if not enough tokens are available to execute the calldata,
                        // the transaction will fail anyway
                        // the error message might not be as explicit though
                        // execute the swap
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, bytes memory res) = _swap.callTo.call{
                            value: nativeValue
                        }(_swap.callData);
                        if (!success) {
                            LibUtil.revertWith(res);
                        }
                        // get post-swap balance
                        uint256 newBalance = LibAsset.getOwnBalance(_swap.receivingAssetId);
                        // emit event
                        emit AssetSwapped(
                            transactionId,
                            _swap.callTo,
                            _swap.sendingAssetId,
                            _swap.receivingAssetId,
                            _swap.fromAmount,
                            newBalance > initialReceivingAssetBalance
                                ? newBalance - initialReceivingAssetBalance
                                : newBalance,
                            block.timestamp
                        );
                    }
                }
                // SPDX-License-Identifier: UNLICENSED
                /// @custom:version 1.0.0
                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: LGPL-3.0-only
                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 SwapperV2
                /// @author LI.FI (https://li.fi)
                /// @notice Abstract contract to provide swap functionality with leftover token handling
                /// @custom:version 1.1.0
                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
                    ) {
                        _;
                        _refundLeftovers(_swaps, _leftoverReceiver, _initialBalances, 0);
                    }
                    /// @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
                    /// @param _nativeReserve Amount of native token to prevent from being swept
                    modifier noLeftoversReserve(
                        LibSwap.SwapData[] calldata _swaps,
                        address payable _leftoverReceiver,
                        uint256[] memory _initialBalances,
                        uint256 _nativeReserve
                    ) {
                        _;
                        _refundLeftovers(
                            _swaps,
                            _leftoverReceiver,
                            _initialBalances,
                            _nativeReserve
                        );
                    }
                    /// @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.NULL_ADDRESS,
                                _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 reserveData = ReserveData({
                            transactionId: _transactionId,
                            leftoverReceiver: _leftoverReceiver,
                            nativeReserve: _nativeReserve
                        });
                        _executeSwaps(reserveData, _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; i < numSwaps; ++i) {
                            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);
                        }
                    }
                    /// @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
                    /// @param _initialBalances Array of initial balances
                    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; i < numSwaps; ++i) {
                            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);
                        }
                    }
                    /// @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
                    ) internal view returns (uint256[] memory) {
                        uint256 numSwaps = _swaps.length;
                        uint256[] memory balances = new uint256[](numSwaps);
                        address asset;
                        for (uint256 i; i < numSwaps; ++i) {
                            asset = _swaps[i].receivingAssetId;
                            balances[i] = LibAsset.getOwnBalance(asset);
                            if (LibAsset.isNativeAsset(asset)) {
                                balances[i] -= msg.value;
                            }
                        }
                        return balances;
                    }
                    /// @dev Refunds leftover tokens to a specified receiver after swaps complete
                    /// @param _swaps Swap data array
                    /// @param _leftoverReceiver Address to send leftover tokens to
                    /// @param _initialBalances Array of initial token balances
                    /// @param _nativeReserve Amount of native token to prevent from being swept (0 for no reserve)
                    function _refundLeftovers(
                        LibSwap.SwapData[] calldata _swaps,
                        address payable _leftoverReceiver,
                        uint256[] memory _initialBalances,
                        uint256 _nativeReserve
                    ) private {
                        uint256 numSwaps = _swaps.length;
                        address finalAsset = _swaps[numSwaps - 1].receivingAssetId;
                        // Handle both intermediate receiving assets and leftover input tokens in a single loop
                        uint256 leftoverAmount;
                        address curAsset;
                        address inputAsset;
                        uint256 curAssetReserve;
                        uint256 currentInputBalance;
                        uint256 inputAssetReserve;
                        for (uint256 i; i < numSwaps; ++i) {
                            // Handle intermediate receiving assets (only for non-final swaps when numSwaps > 1)
                            if (i < numSwaps - 1 && numSwaps != 1) {
                                curAsset = _swaps[i].receivingAssetId;
                                // Handle multiple swap steps
                                if (curAsset != finalAsset) {
                                    leftoverAmount =
                                        LibAsset.getOwnBalance(curAsset) -
                                        _initialBalances[i];
                                    curAssetReserve = LibAsset.isNativeAsset(curAsset)
                                        ? _nativeReserve
                                        : 0;
                                    if (leftoverAmount > curAssetReserve) {
                                        LibAsset.transferAsset(
                                            curAsset,
                                            _leftoverReceiver,
                                            leftoverAmount - curAssetReserve
                                        );
                                    }
                                }
                            }
                            // Handle leftover input tokens (but never sweep the final receiving asset)
                            inputAsset = _swaps[i].sendingAssetId;
                            currentInputBalance = LibAsset.getOwnBalance(inputAsset);
                            inputAssetReserve = LibAsset.isNativeAsset(inputAsset)
                                ? _nativeReserve
                                : 0;
                            // Only transfer leftovers if there's actually a balance remaining after reserve
                            // and if it's not the final receiving asset (which should be kept for bridging)
                            if (
                                currentInputBalance > inputAssetReserve &&
                                inputAsset != finalAsset
                            ) {
                                LibAsset.transferAsset(
                                    inputAsset,
                                    _leftoverReceiver,
                                    currentInputBalance - inputAssetReserve
                                );
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: UNLICENSED
                /// @custom:version 1.0.0
                pragma solidity ^0.8.17;
                import { LibAsset } from "../Libraries/LibAsset.sol";
                import { LibUtil } from "../Libraries/LibUtil.sol";
                // solhint-disable-next-line max-line-length
                import { InvalidReceiver, InformationMismatch, InvalidSendingToken, InvalidAmount, NativeAssetNotSupported, InvalidDestinationChain, CannotBridgeToSameNetwork } from "../Errors/GenericErrors.sol";
                import { ILiFi } from "../Interfaces/ILiFi.sol";
                // solhint-disable-next-line no-unused-import
                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: LGPL-3.0-only
                pragma solidity ^0.8.17;
                /// @title Interface for Mayan
                /// @author LI.FI (https://li.fi)
                /// @custom:version 1.0.0
                interface IMayan {
                    struct PermitParams {
                        uint256 value;
                        uint256 deadline;
                        uint8 v;
                        bytes32 r;
                        bytes32 s;
                    }
                    function forwardEth(
                        address mayanProtocol,
                        bytes calldata protocolData
                    ) external payable;
                    function forwardERC20(
                        address tokenIn,
                        uint256 amountIn,
                        PermitParams calldata permitParams,
                        address mayanProtocol,
                        bytes calldata protocolData
                    ) external payable;
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity ^0.8.17;
                /// @title LiFiData
                /// @author LI.FI (https://li.fi)
                /// @notice A storage for LI.FI-internal config data (addresses, chainIDs, etc.)
                /// @custom:version 1.0.0
                contract LiFiData {
                    address internal constant NON_EVM_ADDRESS =
                        0x11f111f111f111F111f111f111F111f111f111F1;
                    // LI.FI non-EVM Custom Chain IDs (IDs are made up by the LI.FI team)
                    uint256 internal constant LIFI_CHAIN_ID_APTOS = 9271000000000010;
                    uint256 internal constant LIFI_CHAIN_ID_BCH = 20000000000002;
                    uint256 internal constant LIFI_CHAIN_ID_BTC = 20000000000001;
                    uint256 internal constant LIFI_CHAIN_ID_DGE = 20000000000004;
                    uint256 internal constant LIFI_CHAIN_ID_LTC = 20000000000003;
                    uint256 internal constant LIFI_CHAIN_ID_SOLANA = 1151111081099710;
                    uint256 internal constant LIFI_CHAIN_ID_SUI = 9270000000000000;
                    uint256 internal constant LIFI_CHAIN_ID_TRON = 1885080386571452;
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                /// @custom:version 1.0.2
                pragma solidity ^0.8.17;
                error AlreadyInitialized();
                error CannotAuthoriseSelf();
                error CannotBridgeToSameNetwork();
                error ContractCallNotAllowed();
                error CumulativeSlippageTooHigh(uint256 minAmount, uint256 receivedAmount);
                error DiamondIsPaused();
                error ETHTransferFailed();
                error ExternalCallFailed();
                error FunctionDoesNotExist();
                error InformationMismatch();
                error InsufficientBalance(uint256 required, uint256 balance);
                error InvalidAmount();
                error InvalidCallData();
                error InvalidConfig();
                error InvalidContract();
                error InvalidDestinationChain();
                error InvalidFallbackAddress();
                error InvalidNonEVMReceiver();
                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 TransferFromFailed();
                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.4;
                /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
                /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
                /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
                /// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
                ///
                /// @dev Note:
                /// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
                /// - For ERC20s, this implementation won't check that a token has code,
                ///   responsibility is delegated to the caller.
                library SafeTransferLib {
                    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                    /*                       CUSTOM ERRORS                        */
                    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                    /// @dev The ETH transfer has failed.
                    error ETHTransferFailed();
                    /// @dev The ERC20 `transferFrom` has failed.
                    error TransferFromFailed();
                    /// @dev The ERC20 `transfer` has failed.
                    error TransferFailed();
                    /// @dev The ERC20 `approve` has failed.
                    error ApproveFailed();
                    /// @dev The Permit2 operation has failed.
                    error Permit2Failed();
                    /// @dev The Permit2 amount must be less than `2**160 - 1`.
                    error Permit2AmountOverflow();
                    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                    /*                         CONSTANTS                          */
                    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                    /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
                    uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
                    /// @dev Suggested gas stipend for contract receiving ETH to perform a few
                    /// storage reads and writes, but low enough to prevent griefing.
                    uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
                    /// @dev The unique EIP-712 domain domain separator for the DAI token contract.
                    bytes32 internal constant DAI_DOMAIN_SEPARATOR =
                        0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
                    /// @dev The address for the WETH9 contract on Ethereum mainnet.
                    address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
                    /// @dev The canonical Permit2 address.
                    /// [Github](https://github.com/Uniswap/permit2)
                    /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
                    address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
                    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                    /*                       ETH OPERATIONS                       */
                    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                    // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
                    //
                    // The regular variants:
                    // - Forwards all remaining gas to the target.
                    // - Reverts if the target reverts.
                    // - Reverts if the current contract has insufficient balance.
                    //
                    // The force variants:
                    // - Forwards with an optional gas stipend
                    //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
                    // - If the target reverts, or if the gas stipend is exhausted,
                    //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
                    //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
                    // - Reverts if the current contract has insufficient balance.
                    //
                    // The try variants:
                    // - Forwards with a mandatory gas stipend.
                    // - Instead of reverting, returns whether the transfer succeeded.
                    /// @dev Sends `amount` (in wei) ETH to `to`.
                    function safeTransferETH(address to, uint256 amount) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                revert(0x1c, 0x04)
                            }
                        }
                    }
                    /// @dev Sends all the ETH in the current contract to `to`.
                    function safeTransferAllETH(address to) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            // Transfer all the ETH and check if it succeeded or not.
                            if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                revert(0x1c, 0x04)
                            }
                        }
                    }
                    /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
                    function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            if lt(selfbalance(), amount) {
                                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                revert(0x1c, 0x04)
                            }
                            if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                mstore(0x00, to) // Store the address in scratch space.
                                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                            }
                        }
                    }
                    /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
                    function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                mstore(0x00, to) // Store the address in scratch space.
                                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                            }
                        }
                    }
                    /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
                    function forceSafeTransferETH(address to, uint256 amount) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            if lt(selfbalance(), amount) {
                                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                revert(0x1c, 0x04)
                            }
                            if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                mstore(0x00, to) // Store the address in scratch space.
                                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                            }
                        }
                    }
                    /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
                    function forceSafeTransferAllETH(address to) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            // forgefmt: disable-next-item
                            if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                mstore(0x00, to) // Store the address in scratch space.
                                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                            }
                        }
                    }
                    /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
                    function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
                        internal
                        returns (bool success)
                    {
                        /// @solidity memory-safe-assembly
                        assembly {
                            success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
                        }
                    }
                    /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
                    function trySafeTransferAllETH(address to, uint256 gasStipend)
                        internal
                        returns (bool success)
                    {
                        /// @solidity memory-safe-assembly
                        assembly {
                            success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
                        }
                    }
                    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                    /*                      ERC20 OPERATIONS                      */
                    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                    /// Reverts upon failure.
                    ///
                    /// The `from` account must have at least `amount` approved for
                    /// the current contract to manage.
                    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            let m := mload(0x40) // Cache the free memory pointer.
                            mstore(0x60, amount) // Store the `amount` argument.
                            mstore(0x40, to) // Store the `to` argument.
                            mstore(0x2c, shl(96, from)) // Store the `from` argument.
                            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
                            // Perform the transfer, reverting upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                    call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                )
                            ) {
                                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                revert(0x1c, 0x04)
                            }
                            mstore(0x60, 0) // Restore the zero slot to zero.
                            mstore(0x40, m) // Restore the free memory pointer.
                        }
                    }
                    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                    ///
                    /// The `from` account must have at least `amount` approved for the current contract to manage.
                    function trySafeTransferFrom(address token, address from, address to, uint256 amount)
                        internal
                        returns (bool success)
                    {
                        /// @solidity memory-safe-assembly
                        assembly {
                            let m := mload(0x40) // Cache the free memory pointer.
                            mstore(0x60, amount) // Store the `amount` argument.
                            mstore(0x40, to) // Store the `to` argument.
                            mstore(0x2c, shl(96, from)) // Store the `from` argument.
                            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
                            success :=
                                and( // The arguments of `and` are evaluated from right to left.
                                    or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                    call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                )
                            mstore(0x60, 0) // Restore the zero slot to zero.
                            mstore(0x40, m) // Restore the free memory pointer.
                        }
                    }
                    /// @dev Sends all of ERC20 `token` from `from` to `to`.
                    /// Reverts upon failure.
                    ///
                    /// The `from` account must have their entire balance approved for the current contract to manage.
                    function safeTransferAllFrom(address token, address from, address to)
                        internal
                        returns (uint256 amount)
                    {
                        /// @solidity memory-safe-assembly
                        assembly {
                            let m := mload(0x40) // Cache the free memory pointer.
                            mstore(0x40, to) // Store the `to` argument.
                            mstore(0x2c, shl(96, from)) // Store the `from` argument.
                            mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
                            // Read the balance, reverting upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                    staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                                )
                            ) {
                                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                revert(0x1c, 0x04)
                            }
                            mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
                            amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
                            // Perform the transfer, reverting upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                    call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                )
                            ) {
                                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                revert(0x1c, 0x04)
                            }
                            mstore(0x60, 0) // Restore the zero slot to zero.
                            mstore(0x40, m) // Restore the free memory pointer.
                        }
                    }
                    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
                    /// Reverts upon failure.
                    function safeTransfer(address token, address to, uint256 amount) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            mstore(0x14, to) // Store the `to` argument.
                            mstore(0x34, amount) // Store the `amount` argument.
                            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
                            // Perform the transfer, reverting upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                )
                            ) {
                                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                revert(0x1c, 0x04)
                            }
                            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                        }
                    }
                    /// @dev Sends all of ERC20 `token` from the current contract to `to`.
                    /// Reverts upon failure.
                    function safeTransferAll(address token, address to) internal returns (uint256 amount) {
                        /// @solidity memory-safe-assembly
                        assembly {
                            mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
                            mstore(0x20, address()) // Store the address of the current contract.
                            // Read the balance, reverting upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                    staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                                )
                            ) {
                                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                revert(0x1c, 0x04)
                            }
                            mstore(0x14, to) // Store the `to` argument.
                            amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
                            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
                            // Perform the transfer, reverting upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                )
                            ) {
                                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                revert(0x1c, 0x04)
                            }
                            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                        }
                    }
                    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
                    /// Reverts upon failure.
                    function safeApprove(address token, address to, uint256 amount) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            mstore(0x14, to) // Store the `to` argument.
                            mstore(0x34, amount) // Store the `amount` argument.
                            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                            // Perform the approval, reverting upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                )
                            ) {
                                mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                                revert(0x1c, 0x04)
                            }
                            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                        }
                    }
                    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
                    /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
                    /// then retries the approval again (some tokens, e.g. USDT, requires this).
                    /// Reverts upon failure.
                    function safeApproveWithRetry(address token, address to, uint256 amount) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            mstore(0x14, to) // Store the `to` argument.
                            mstore(0x34, amount) // Store the `amount` argument.
                            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                            // Perform the approval, retrying upon failure.
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                )
                            ) {
                                mstore(0x34, 0) // Store 0 for the `amount`.
                                mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                                pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                                mstore(0x34, amount) // Store back the original `amount`.
                                // Retry the approval, reverting upon failure.
                                if iszero(
                                    and(
                                        or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                        call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                    )
                                ) {
                                    mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                                    revert(0x1c, 0x04)
                                }
                            }
                            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                        }
                    }
                    /// @dev Returns the amount of ERC20 `token` owned by `account`.
                    /// Returns zero if the `token` does not exist.
                    function balanceOf(address token, address account) internal view returns (uint256 amount) {
                        /// @solidity memory-safe-assembly
                        assembly {
                            mstore(0x14, account) // Store the `account` argument.
                            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
                            amount :=
                                mul( // The arguments of `mul` are evaluated from right to left.
                                    mload(0x20),
                                    and( // The arguments of `and` are evaluated from right to left.
                                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                        staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                                    )
                                )
                        }
                    }
                    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                    /// If the initial attempt fails, try to use Permit2 to transfer the token.
                    /// Reverts upon failure.
                    ///
                    /// The `from` account must have at least `amount` approved for the current contract to manage.
                    function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
                        if (!trySafeTransferFrom(token, from, to, amount)) {
                            permit2TransferFrom(token, from, to, amount);
                        }
                    }
                    /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
                    /// Reverts upon failure.
                    function permit2TransferFrom(address token, address from, address to, uint256 amount)
                        internal
                    {
                        /// @solidity memory-safe-assembly
                        assembly {
                            let m := mload(0x40)
                            mstore(add(m, 0x74), shr(96, shl(96, token)))
                            mstore(add(m, 0x54), amount)
                            mstore(add(m, 0x34), to)
                            mstore(add(m, 0x20), shl(96, from))
                            // `transferFrom(address,address,uint160,address)`.
                            mstore(m, 0x36c78516000000000000000000000000)
                            let p := PERMIT2
                            let exists := eq(chainid(), 1)
                            if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
                            if iszero(and(call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00), exists)) {
                                mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                                revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
                            }
                        }
                    }
                    /// @dev Permit a user to spend a given amount of
                    /// another user's tokens via native EIP-2612 permit if possible, falling
                    /// back to Permit2 if native permit fails or is not implemented on the token.
                    function permit2(
                        address token,
                        address owner,
                        address spender,
                        uint256 amount,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal {
                        bool success;
                        /// @solidity memory-safe-assembly
                        assembly {
                            for {} shl(96, xor(token, WETH9)) {} {
                                mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                                if iszero(
                                    and( // The arguments of `and` are evaluated from right to left.
                                        lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                                        // Gas stipend to limit gas burn for tokens that don't refund gas when
                                        // an non-existing function is called. 5K should be enough for a SLOAD.
                                        staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                                    )
                                ) { break }
                                // After here, we can be sure that token is a contract.
                                let m := mload(0x40)
                                mstore(add(m, 0x34), spender)
                                mstore(add(m, 0x20), shl(96, owner))
                                mstore(add(m, 0x74), deadline)
                                if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                                    mstore(0x14, owner)
                                    mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                                    mstore(add(m, 0x94), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                                    mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                                    // `nonces` is already at `add(m, 0x54)`.
                                    // `1` is already stored at `add(m, 0x94)`.
                                    mstore(add(m, 0xb4), and(0xff, v))
                                    mstore(add(m, 0xd4), r)
                                    mstore(add(m, 0xf4), s)
                                    success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                                    break
                                }
                                mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                                mstore(add(m, 0x54), amount)
                                mstore(add(m, 0x94), and(0xff, v))
                                mstore(add(m, 0xb4), r)
                                mstore(add(m, 0xd4), s)
                                success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                                break
                            }
                        }
                        if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
                    }
                    /// @dev Simple permit on the Permit2 contract.
                    function simplePermit2(
                        address token,
                        address owner,
                        address spender,
                        uint256 amount,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal {
                        /// @solidity memory-safe-assembly
                        assembly {
                            let m := mload(0x40)
                            mstore(m, 0x927da105) // `allowance(address,address,address)`.
                            {
                                let addressMask := shr(96, not(0))
                                mstore(add(m, 0x20), and(addressMask, owner))
                                mstore(add(m, 0x40), and(addressMask, token))
                                mstore(add(m, 0x60), and(addressMask, spender))
                                mstore(add(m, 0xc0), and(addressMask, spender))
                            }
                            let p := mul(PERMIT2, iszero(shr(160, amount)))
                            if iszero(
                                and( // The arguments of `and` are evaluated from right to left.
                                    gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                                    staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                                )
                            ) {
                                mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                                revert(add(0x18, shl(2, iszero(p))), 0x04)
                            }
                            mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
                            // `owner` is already `add(m, 0x20)`.
                            // `token` is already at `add(m, 0x40)`.
                            mstore(add(m, 0x60), amount)
                            mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
                            // `nonce` is already at `add(m, 0xa0)`.
                            // `spender` is already at `add(m, 0xc0)`.
                            mstore(add(m, 0xe0), deadline)
                            mstore(add(m, 0x100), 0x100) // `signature` offset.
                            mstore(add(m, 0x120), 0x41) // `signature` length.
                            mstore(add(m, 0x140), r)
                            mstore(add(m, 0x160), s)
                            mstore(add(m, 0x180), shl(248, v))
                            if iszero(call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00)) {
                                mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                                revert(0x1c, 0x04)
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
                pragma solidity ^0.8.0;
                import "../IERC20.sol";
                /**
                 * @dev Interface for the optional metadata functions from the ERC20 standard.
                 *
                 * _Available since v4.1._
                 */
                interface IERC20Metadata is IERC20 {
                    /**
                     * @dev Returns the name of the token.
                     */
                    function name() external view returns (string memory);
                    /**
                     * @dev Returns the symbol of the token.
                     */
                    function symbol() external view returns (string memory);
                    /**
                     * @dev Returns the decimals places of the token.
                     */
                    function decimals() external view returns (uint8);
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Provides information about the current execution context, including the
                 * sender of the transaction and its data. While these are generally available
                 * via msg.sender and msg.data, they should not be accessed in such a direct
                 * manner, since when dealing with meta-transactions the account sending and
                 * paying for execution may not be the actual sender (as far as an application
                 * is concerned).
                 *
                 * This contract is only required for intermediate, library-like contracts.
                 */
                abstract contract Context {
                    function _msgSender() internal view virtual returns (address) {
                        return msg.sender;
                    }
                    function _msgData() internal view virtual returns (bytes calldata) {
                        return msg.data;
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                /// @custom:version 1.0.0
                pragma solidity ^0.8.17;
                // solhint-disable-next-line no-global-import
                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);
                    }
                    function revertWith(bytes memory data) internal pure {
                        assembly {
                            let dataSize := mload(data) // Load the size of the data
                            let dataPtr := add(data, 0x20) // Advance data pointer to the next word
                            revert(dataPtr, dataSize) // Revert with the given data
                        }
                    }
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                /// @custom:version 1.0.0
                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: LGPL-3.0-only
                /// @custom:version 1.0.0
                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;
                        }
                        // solhint-disable-next-line gas-custom-errors
                        require(value == 0, "Strings: hex length insufficient");
                        return string(buffer);
                    }
                }
                

                File 5 of 5: Wormhole
                // contracts/Wormhole.sol
                // SPDX-License-Identifier: Apache 2
                pragma solidity ^0.8.0;
                import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
                contract Wormhole is ERC1967Proxy {
                    constructor (address implementation, bytes memory initData) ERC1967Proxy(
                        implementation,
                        initData
                    ) { }
                }// SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "../Proxy.sol";
                import "./ERC1967Upgrade.sol";
                /**
                 * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
                 * implementation address that can be changed. This address is stored in storage in the location specified by
                 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
                 * implementation behind the proxy.
                 */
                contract ERC1967Proxy is Proxy, ERC1967Upgrade {
                    /**
                     * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
                     *
                     * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
                     * function call, and allows initializating the storage of the proxy like a Solidity constructor.
                     */
                    constructor(address _logic, bytes memory _data) payable {
                        assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
                        _upgradeToAndCall(_logic, _data, false);
                    }
                    /**
                     * @dev Returns the current implementation address.
                     */
                    function _implementation() internal view virtual override returns (address impl) {
                        return ERC1967Upgrade._getImplementation();
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.2;
                import "../beacon/IBeacon.sol";
                import "../../utils/Address.sol";
                import "../../utils/StorageSlot.sol";
                /**
                 * @dev This abstract contract provides getters and event emitting update functions for
                 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
                 *
                 * _Available since v4.1._
                 *
                 * @custom:oz-upgrades-unsafe-allow delegatecall
                 */
                abstract contract ERC1967Upgrade {
                    // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
                    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
                    /**
                     * @dev Storage slot with the address of the current implementation.
                     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
                     * validated in the constructor.
                     */
                    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                    /**
                     * @dev Emitted when the implementation is upgraded.
                     */
                    event Upgraded(address indexed implementation);
                    /**
                     * @dev Returns the current implementation address.
                     */
                    function _getImplementation() internal view returns (address) {
                        return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
                    }
                    /**
                     * @dev Stores a new address in the EIP1967 implementation slot.
                     */
                    function _setImplementation(address newImplementation) private {
                        require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                        StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
                    }
                    /**
                     * @dev Perform implementation upgrade
                     *
                     * Emits an {Upgraded} event.
                     */
                    function _upgradeTo(address newImplementation) internal {
                        _setImplementation(newImplementation);
                        emit Upgraded(newImplementation);
                    }
                    /**
                     * @dev Perform implementation upgrade with additional setup call.
                     *
                     * Emits an {Upgraded} event.
                     */
                    function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
                        _setImplementation(newImplementation);
                        emit Upgraded(newImplementation);
                        if (data.length > 0 || forceCall) {
                            Address.functionDelegateCall(newImplementation, data);
                        }
                    }
                    /**
                     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
                     *
                     * Emits an {Upgraded} event.
                     */
                    function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {
                        address oldImplementation = _getImplementation();
                        // Initial upgrade and setup call
                        _setImplementation(newImplementation);
                        if (data.length > 0 || forceCall) {
                            Address.functionDelegateCall(newImplementation, data);
                        }
                        // Perform rollback test if not already in progress
                        StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
                        if (!rollbackTesting.value) {
                            // Trigger rollback using upgradeTo from the new implementation
                            rollbackTesting.value = true;
                            Address.functionDelegateCall(
                                newImplementation,
                                abi.encodeWithSignature(
                                    "upgradeTo(address)",
                                    oldImplementation
                                )
                            );
                            rollbackTesting.value = false;
                            // Check rollback was effective
                            require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
                            // Finally reset to the new implementation and log the upgrade
                            _setImplementation(newImplementation);
                            emit Upgraded(newImplementation);
                        }
                    }
                    /**
                     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
                     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
                     *
                     * Emits a {BeaconUpgraded} event.
                     */
                    function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
                        _setBeacon(newBeacon);
                        emit BeaconUpgraded(newBeacon);
                        if (data.length > 0 || forceCall) {
                            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
                        }
                    }
                    /**
                     * @dev Storage slot with the admin of the contract.
                     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
                     * validated in the constructor.
                     */
                    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
                    /**
                     * @dev Emitted when the admin account has changed.
                     */
                    event AdminChanged(address previousAdmin, address newAdmin);
                    /**
                     * @dev Returns the current admin.
                     */
                    function _getAdmin() internal view returns (address) {
                        return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
                    }
                    /**
                     * @dev Stores a new address in the EIP1967 admin slot.
                     */
                    function _setAdmin(address newAdmin) private {
                        require(newAdmin != address(0), "ERC1967: new admin is the zero address");
                        StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
                    }
                    /**
                     * @dev Changes the admin of the proxy.
                     *
                     * Emits an {AdminChanged} event.
                     */
                    function _changeAdmin(address newAdmin) internal {
                        emit AdminChanged(_getAdmin(), newAdmin);
                        _setAdmin(newAdmin);
                    }
                    /**
                     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
                     * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
                     */
                    bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
                    /**
                     * @dev Emitted when the beacon is upgraded.
                     */
                    event BeaconUpgraded(address indexed beacon);
                    /**
                     * @dev Returns the current beacon.
                     */
                    function _getBeacon() internal view returns (address) {
                        return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
                    }
                    /**
                     * @dev Stores a new beacon in the EIP1967 beacon slot.
                     */
                    function _setBeacon(address newBeacon) private {
                        require(
                            Address.isContract(newBeacon),
                            "ERC1967: new beacon is not a contract"
                        );
                        require(
                            Address.isContract(IBeacon(newBeacon).implementation()),
                            "ERC1967: beacon implementation is not a contract"
                        );
                        StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                /**
                 * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
                 * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
                 * be specified by overriding the virtual {_implementation} function.
                 *
                 * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
                 * different contract through the {_delegate} function.
                 *
                 * The success and return data of the delegated call will be returned back to the caller of the proxy.
                 */
                abstract contract Proxy {
                    /**
                     * @dev Delegates the current call to `implementation`.
                     *
                     * This function does not return to its internall call site, it will return directly to the external caller.
                     */
                    function _delegate(address implementation) internal virtual {
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            // Copy msg.data. We take full control of memory in this inline assembly
                            // block because it will not return to Solidity code. We overwrite the
                            // Solidity scratch pad at memory position 0.
                            calldatacopy(0, 0, calldatasize())
                            // Call the implementation.
                            // out and outsize are 0 because we don't know the size yet.
                            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                            // Copy the returned data.
                            returndatacopy(0, 0, returndatasize())
                            switch result
                            // delegatecall returns 0 on error.
                            case 0 { revert(0, returndatasize()) }
                            default { return(0, returndatasize()) }
                        }
                    }
                    /**
                     * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
                     * and {_fallback} should delegate.
                     */
                    function _implementation() internal view virtual returns (address);
                    /**
                     * @dev Delegates the current call to the address returned by `_implementation()`.
                     *
                     * This function does not return to its internall call site, it will return directly to the external caller.
                     */
                    function _fallback() internal virtual {
                        _beforeFallback();
                        _delegate(_implementation());
                    }
                    /**
                     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
                     * function in the contract matches the call data.
                     */
                    fallback () external payable virtual {
                        _fallback();
                    }
                    /**
                     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
                     * is empty.
                     */
                    receive () external payable virtual {
                        _fallback();
                    }
                    /**
                     * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
                     * call, or as part of the Solidity `fallback` or `receive` functions.
                     *
                     * If overriden should call `super._beforeFallback()`.
                     */
                    function _beforeFallback() internal virtual {
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                /**
                 * @dev This is the interface that {BeaconProxy} expects of its beacon.
                 */
                interface IBeacon {
                    /**
                     * @dev Must return an address that can be used as a delegate call target.
                     *
                     * {BeaconProxy} will check that this address is a contract.
                     */
                    function implementation() external view returns (address);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                /**
                 * @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
                     * ====
                     */
                    function isContract(address account) internal view returns (bool) {
                        // This method relies on extcodesize, which returns 0 for contracts in
                        // construction, since the code is only stored at the end of the
                        // constructor execution.
                        uint256 size;
                        // solhint-disable-next-line no-inline-assembly
                        assembly { size := extcodesize(account) }
                        return size > 0;
                    }
                    /**
                     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                     * `recipient`, forwarding all available gas and reverting on errors.
                     *
                     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                     * of certain opcodes, possibly making contracts go over the 2300 gas limit
                     * imposed by `transfer`, making them unable to receive funds via
                     * `transfer`. {sendValue} removes this limitation.
                     *
                     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                     *
                     * IMPORTANT: because control is transferred to `recipient`, care must be
                     * taken to not create reentrancy vulnerabilities. Consider using
                     * {ReentrancyGuard} or the
                     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                     */
                    function sendValue(address payable recipient, uint256 amount) internal {
                        require(address(this).balance >= amount, "Address: insufficient balance");
                        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                        (bool success, ) = recipient.call{ value: amount }("");
                        require(success, "Address: unable to send value, recipient may have reverted");
                    }
                    /**
                     * @dev Performs a Solidity function call using a low level `call`. A
                     * plain`call` is an unsafe replacement for a function call: use this
                     * function instead.
                     *
                     * If `target` reverts with a revert reason, it is bubbled up by this
                     * function (like regular Solidity function calls).
                     *
                     * Returns the raw returned data. To convert to the expected return value,
                     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                     *
                     * Requirements:
                     *
                     * - `target` must be a contract.
                     * - calling `target` with `data` must not revert.
                     *
                     * _Available since v3.1._
                     */
                    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                      return functionCall(target, data, "Address: low-level call failed");
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                     * `errorMessage` as a fallback revert reason when `target` reverts.
                     *
                     * _Available since v3.1._
                     */
                    function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                        return functionCallWithValue(target, data, 0, errorMessage);
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                     * but also transferring `value` wei to `target`.
                     *
                     * Requirements:
                     *
                     * - the calling contract must have an ETH balance of at least `value`.
                     * - the called Solidity function must be `payable`.
                     *
                     * _Available since v3.1._
                     */
                    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                    }
                    /**
                     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                     * with `errorMessage` as a fallback revert reason when `target` reverts.
                     *
                     * _Available since v3.1._
                     */
                    function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                        require(address(this).balance >= value, "Address: insufficient balance for call");
                        require(isContract(target), "Address: call to non-contract");
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, bytes memory returndata) = target.call{ value: value }(data);
                        return _verifyCallResult(success, returndata, errorMessage);
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                     * but performing a static call.
                     *
                     * _Available since v3.3._
                     */
                    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                        return functionStaticCall(target, data, "Address: low-level static call failed");
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                     * but performing a static call.
                     *
                     * _Available since v3.3._
                     */
                    function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                        require(isContract(target), "Address: static call to non-contract");
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, bytes memory returndata) = target.staticcall(data);
                        return _verifyCallResult(success, returndata, errorMessage);
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                     * but performing a delegate call.
                     *
                     * _Available since v3.4._
                     */
                    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                     * but performing a delegate call.
                     *
                     * _Available since v3.4._
                     */
                    function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                        require(isContract(target), "Address: delegate call to non-contract");
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, bytes memory returndata) = target.delegatecall(data);
                        return _verifyCallResult(success, returndata, errorMessage);
                    }
                    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                        if (success) {
                            return returndata;
                        } else {
                            // Look for revert reason and bubble it up if present
                            if (returndata.length > 0) {
                                // The easiest way to bubble the revert reason is using memory via assembly
                                // solhint-disable-next-line no-inline-assembly
                                assembly {
                                    let returndata_size := mload(returndata)
                                    revert(add(32, returndata), returndata_size)
                                }
                            } else {
                                revert(errorMessage);
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                /**
                 * @dev Library for reading and writing primitive types to specific storage slots.
                 *
                 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
                 * This library helps with reading and writing to such slots without the need for inline assembly.
                 *
                 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
                 *
                 * Example usage to set ERC1967 implementation slot:
                 * ```
                 * contract ERC1967 {
                 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                 *
                 *     function _getImplementation() internal view returns (address) {
                 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
                 *     }
                 *
                 *     function _setImplementation(address newImplementation) internal {
                 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
                 *     }
                 * }
                 * ```
                 *
                 * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
                 */
                library StorageSlot {
                    struct AddressSlot {
                        address value;
                    }
                    struct BooleanSlot {
                        bool value;
                    }
                    struct Bytes32Slot {
                        bytes32 value;
                    }
                    struct Uint256Slot {
                        uint256 value;
                    }
                    /**
                     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
                     */
                    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                        assembly {
                            r.slot := slot
                        }
                    }
                    /**
                     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
                     */
                    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                        assembly {
                            r.slot := slot
                        }
                    }
                    /**
                     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
                     */
                    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                        assembly {
                            r.slot := slot
                        }
                    }
                    /**
                     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
                     */
                    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                        assembly {
                            r.slot := slot
                        }
                    }
                }