ETH Price: $2,499.31 (+2.40%)

Transaction Decoder

Block:
17314375 at May-22-2023 10:54:59 AM +UTC
Transaction Fee:
0.007259215043876675 ETH $18.14
Gas Used:
244,717 Gas / 29.663713775 Gwei

Emitted Events:

85 AggregationRouterV5.OrderFilled( maker=0xA7dcF4FB18843CE3c7a6Fbf3974Fd30Ad53bb8d1, orderHash=99EF70EE1F4DB7AF660B261D9FC0584CD0C9C597E46282971653D012ADFB1FC4, remaining=0 )
86 FRAXShares.VoterVotesChanged( voter=0xA7dcF4FB18843CE3c7a6Fbf3974Fd30Ad53bb8d1, previousBalance=254667264744670363648, newBalance=0 )
87 FRAXShares.VoterVotesChanged( voter=[Receiver] 0x7e252a31add34d0372950f482c38650231f3967c, previousBalance=5243684431898719267924, newBalance=5498351696643389631572 )
88 FRAXShares.Transfer( from=0xA7dcF4FB18843CE3c7a6Fbf3974Fd30Ad53bb8d1, to=[Receiver] 0x7e252a31add34d0372950f482c38650231f3967c, value=254667264744670363648 )
89 FRAXShares.Approval( owner=0xA7dcF4FB18843CE3c7a6Fbf3974Fd30Ad53bb8d1, spender=AggregationRouterV5, value=115792089237316195423570985008687907853269984665640564036613478684964985962495 )
90 WETH9.Transfer( src=[Receiver] 0x7e252a31add34d0372950f482c38650231f3967c, dst=Settlement, wad=1014655416821342478 )
91 WETH9.Approval( src=Settlement, guy=AggregationRouterV5, wad=1014655416821342478 )
92 WETH9.Transfer( src=Settlement, dst=WethUnwrapper, wad=1014655416821342478 )
93 WETH9.Withdrawal( src=WethUnwrapper, wad=1014655416821342478 )

Account State Difference:

  Address   Before After State Difference Code
0x11111112...73A960582
(Aggregation Router V5)
0x3432B6A6...9D9C964D0
(builder0x69)
1.376325343969770301 Eth1.376950550940224004 Eth0.000625206970453703
0x73b3BF60...aE33f9255
1.360339389904601454 Eth
Nonce: 550
1.353080174860724779 Eth
Nonce: 551
0.007259215043876675
0xA7dcF4FB...Ad53bb8d1 3.520287646589756061 Eth4.534943063411098539 Eth1.014655416821342478
0xC02aaA39...83C756Cc2 3,508,682.485708645489309183 Eth3,508,681.471053228667966705 Eth1.014655416821342478

Execution Trace

0x7e252a31add34d0372950f482c38650231f3967c.2076d341( )
  • FRAXShares.balanceOf( account=0x7E252a31aDD34D0372950F482c38650231f3967c ) => ( 5243684431898719267924 )
  • Settlement.settleOrders( data=0x00000000000000000000000000000000000000000000000000000000000000E0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000003E000000000000000000000000000000000000000000000000DCE37E0001270000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000E15240212A185000000000000000000000000007E252A31ADD34D0372950F482C38650231F3967C646B49F70000B4029EE200000000000000004EDD29061764BC74D9023DBA9A1C0000000000000000000000003432B6A60D23CA0DFCA7761B7AB56459D9C964D0000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2000000000000000000000000A7DCF4FB18843CE3C7A6FBF3974FD30AD53BB8D100000000000000000000000008B067AD41E45BABE5BBB52FC2FE7F692F628B06000000000000000000000000A88800CD213DA5AE406CE248380802BD53B4764700000000000000000000000000000000000000000000000DCE37E000127000000000000000000000000000000000000000000000000000000DE602983B7855750000003800000024000000240000002400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000001322CC2878D0000646B4AB6000000000000A7DCF4FB18843CE3C7A6FBF3974FD30AD53BB8D108B067AD41E45BABE5BBB52FC2FE7F692F628B06001801641200000000CB13E91F957DE7FB5F77A7E933FE04BC464F895D00000000C6C7565644EA1893AD29182F7B6961AAB7EDFED000000000D1742B3C4FBB096990C8950FA635AEC75B30781A000000000B8A49D816CC709B6EADB09498030AE3416B66DC00000000BD4DBE0CB9136FFB4955EDE88EBD5E92222AD09A000000007E252A31ADD34D0372950F482C38650231F3967C0000000069313AEC23DB7E4E8788B942850202BCB603873400000000EE230DD7519BC5D0C9899E8704FFDC80560E8509000000009108813F22637385228A1C621C1904BBBC50DC2500000000FA1578C380311A1C4171EE5386AB87D67CC14AC7FFFFFFFF5100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040C724839167119AF70E9C5383BBFAB6FD9B3FA1BA2CB91B7449C41749B34C5A4093F6F07CF55F1A8B7DB193B42C3D541597A244C3E8B2F63A16E787D8FBE0809B0000000000000000000000000000000000000000000000000000000000000049A88800CD213DA5AE406CE248380802BD53B47647017E252A31ADD34D0372950F482C38650231F3967C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 )
    • Null: 0x000...004.STATICCALL( )
    • AggregationRouterV5.fillOrderTo( order_=[{name:salt, type:uint256, order:1, indexed:false, value:45420847980848357723260306187375535797986348647939513174235427038513308801564, valueString:45420847980848357723260306187375535797986348647939513174235427038513308801564}, {name:makerAsset, type:address, order:2, indexed:false, value:0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0, valueString:0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0}, {name:takerAsset, type:address, order:3, indexed:false, value:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, valueString:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2}, {name:maker, type:address, order:4, indexed:false, value:0xA7dcF4FB18843CE3c7a6Fbf3974Fd30Ad53bb8d1, valueString:0xA7dcF4FB18843CE3c7a6Fbf3974Fd30Ad53bb8d1}, {name:receiver, type:address, order:5, indexed:false, value:0x08B067ad41e45bAbE5bBb52Fc2fE7f692F628b06, valueString:0x08B067ad41e45bAbE5bBb52Fc2fE7f692F628b06}, {name:allowedSender, type:address, order:6, indexed:false, value:0xA88800CD213dA5Ae406ce248380802BD53b47647, valueString:0xA88800CD213dA5Ae406ce248380802BD53b47647}, {name:makingAmount, type:uint256, order:7, indexed:false, value:254667264744670363648, valueString:254667264744670363648}, {name:takingAmount, type:uint256, order:8, indexed:false, value:1001490819992540533, valueString:1001490819992540533}, {name:offsets, type:uint256, order:9, indexed:false, value:1509757013586411491027887411327350407223642517304424529517664643579904, valueString:1509757013586411491027887411327350407223642517304424529517664643579904}, {name:interactions, type:bytes, order:10, indexed:false, value:0x2CC2878D0000646B4AB6000000000000A7DCF4FB18843CE3C7A6FBF3974FD30AD53BB8D108B067AD41E45BABE5BBB52FC2FE7F692F628B06001801641200000000CB13E91F957DE7FB5F77A7E933FE04BC464F895D00000000C6C7565644EA1893AD29182F7B6961AAB7EDFED000000000D1742B3C4FBB096990C8950FA635AEC75B30781A000000000B8A49D816CC709B6EADB09498030AE3416B66DC00000000BD4DBE0CB9136FFB4955EDE88EBD5E92222AD09A000000007E252A31ADD34D0372950F482C38650231F3967C0000000069313AEC23DB7E4E8788B942850202BCB603873400000000EE230DD7519BC5D0C9899E8704FFDC80560E8509000000009108813F22637385228A1C621C1904BBBC50DC2500000000FA1578C380311A1C4171EE5386AB87D67CC14AC7FFFFFFFF51, valueString:0x2CC2878D0000646B4AB6000000000000A7DCF4FB18843CE3C7A6FBF3974FD30AD53BB8D108B067AD41E45BABE5BBB52FC2FE7F692F628B06001801641200000000CB13E91F957DE7FB5F77A7E933FE04BC464F895D00000000C6C7565644EA1893AD29182F7B6961AAB7EDFED000000000D1742B3C4FBB096990C8950FA635AEC75B30781A000000000B8A49D816CC709B6EADB09498030AE3416B66DC00000000BD4DBE0CB9136FFB4955EDE88EBD5E92222AD09A000000007E252A31ADD34D0372950F482C38650231F3967C0000000069313AEC23DB7E4E8788B942850202BCB603873400000000EE230DD7519BC5D0C9899E8704FFDC80560E8509000000009108813F22637385228A1C621C1904BBBC50DC2500000000FA1578C380311A1C4171EE5386AB87D67CC14AC7FFFFFFFF51}], signature=0xC724839167119AF70E9C5383BBFAB6FD9B3FA1BA2CB91B7449C41749B34C5A4093F6F07CF55F1A8B7DB193B42C3D541597A244C3E8B2F63A16E787D8FBE0809B, interaction=0xA88800CD213DA5AE406CE248380802BD53B47647017E252A31ADD34D0372950F482C38650231F3967C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007E252A31ADD34D0372950F482C38650231F3967C000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2000000000000000000000000000000000000000000000000000000000002017A00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, makingAmount=254667264744670363648, takingAmount=0, skipPermitAndThresholdAmount=1014756882363024640, target=0x7E252a31aDD34D0372950F482c38650231f3967c ) => ( actualMakingAmount=254667264744670363648, actualTakingAmount=1014655416821342478, orderHash=99EF70EE1F4DB7AF660B261D9FC0584CD0C9C597E46282971653D012ADFB1FC4 )
      • Null: 0x000...001.99ef70ee( )
      • FRAXShares.transferFrom( sender=0xA7dcF4FB18843CE3c7a6Fbf3974Fd30Ad53bb8d1, recipient=0x7E252a31aDD34D0372950F482c38650231f3967c, amount=254667264744670363648 ) => ( True )
      • Settlement.fillOrderInteraction( taker=0xA88800CD213dA5Ae406ce248380802BD53b47647, 254667264744670363648, takingAmount=1001490819992540533, interactiveData=0x017E252A31ADD34D0372950F482C38650231F3967C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007E252A31ADD34D0372950F482C38650231F3967C000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2000000000000000000000000000000000000000000000000000000000002017A00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ) => ( result=1014655416821342478 )
        • 0x7e252a31add34d0372950f482c38650231f3967c.1944799f( )
          • WETH9.transfer( dst=0xA88800CD213dA5Ae406ce248380802BD53b47647, wad=1014655416821342478 ) => ( True )
          • WETH9.approve( guy=0x1111111254EEB25477B68fb85Ed929f73A960582, wad=1014655416821342478 ) => ( True )
          • WETH9.transferFrom( src=0xA88800CD213dA5Ae406ce248380802BD53b47647, dst=0x08B067ad41e45bAbE5bBb52Fc2fE7f692F628b06, wad=1014655416821342478 ) => ( True )
          • WethUnwrapper.fillOrderPostInteraction( 99EF70EE1F4DB7AF660B261D9FC0584CD0C9C597E46282971653D012ADFB1FC4, maker=0xA7dcF4FB18843CE3c7a6Fbf3974Fd30Ad53bb8d1, 0xA88800CD213dA5Ae406ce248380802BD53b47647, 254667264744670363648, takingAmount=1014655416821342478, 0, interactiveData=0x )
            • WETH9.withdraw( wad=1014655416821342478 )
              • ETH 1.014655416821342478 WethUnwrapper.CALL( )
              • ETH 1.014655416821342478 0xa7dcf4fb18843ce3c7a6fbf3974fd30ad53bb8d1.CALL( )
              • FRAXShares.balanceOf( account=0x7E252a31aDD34D0372950F482c38650231f3967c ) => ( 5498351696643389631572 )
                File 1 of 5: AggregationRouterV5
                /*
                                                                           ,▄▓▓██▌   ,╓▄▄▓▓▓▓▓▓▓▓▄▄▄,,
                                                                        ,▓██▓███▓▄▓███▓╬╬╬╬╬╬╬╬╬╬╬╬╬▓███▓▄,
                                                                  ▄█   ▓██╬╣███████╬▓▀╬╬▓▓▓████████████▓█████▄,
                                                                 ▓██▌ ▓██╬╣██████╬▓▌  ██████████████████████▌╙╙▀ⁿ
                                                                ▐████████╬▓████▓▓█╨ ▄ ╟█████████▓▓╬╬╬╬╬▓▓█████▓▄
                                                  └▀▓▓▄╓        ╟█▓╣█████▓██████▀ ╓█▌ ███████▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬╬▓██▓▄
                                                     └▀████▓▄╥  ▐██╬╬██████████╙ Æ▀─ ▓███▀╚╠╬╩▀▀███████▓▓╬╬╬╬╬╬╬╬╬██▄
                                                        └▀██▓▀▀█████▓╬▓██████▀     ▄█████▒╠"      └╙▓██████▓╬╬╬╬╬╬╬╬██▄
                                                           └▀██▄,└╙▀▀████▌└╙    ^"▀╙╙╙"╙██      @▄    ╙▀███████╬╬╬╬╬╬╬██µ
                                                              └▀██▓▄, ██▌       ╒       ╙█▓     ]▓█▓╔    ▀███████▓╬╬╬╬╬▓█▌
                                                                  ▀█████       ▓         ╟█▌    ]╠██▓░▒╓   ▀████████╬╬╬╬╣█▌
                                                                  ▐████      ╓█▀█▌      ,██▌    ╚Å███▓▒▒╠╓  ╙█████████╬╬╬╣█▌
                                                                  └████     ▓█░░▓█      ▀▀▀    φ▒╫████▒▒▒▒╠╓  █████████▓╬╬▓█µ
                                                                   ╘███µ ▌▄█▓▄▓▀`     ,▀    ,╔╠░▓██████▌╠▒▒▒φ  ██████████╬╬██
                                                                   ▐████µ╙▓▀`     ,▀╙,╔╔φφφ╠░▄▓███████▌░▓╙▒▒▒╠ └██╬███████╬▓█⌐
                                                                   ╫██ ▓▌         ▌φ▒▒░▓██████████████▌▒░▓╚▒▒▒╠ ▓██╬▓██████╣█▌
                                                                   ██▌           ▌╔▒▒▄████████████████▒▒▒░▌╠▒▒▒≥▐██▓╬╬███████▌
                                                                   ██▌      ,╓φ╠▓«▒▒▓████▀  ▀█████████▌▒▒▒╟░▒▒▒▒▐███╬╬╣████▓█▌
                                                                  ▐██      ╠▒▄▓▓███▓████└     ▀████████▌▒▒░▌╚▒▒▒▐███▓╬╬████ ╙▌
                                                                  ███  )  ╠▒░░░▒░╬████▀        └████████░▒▒░╬∩▒▒▓████╬╬╣███
                                                                 ▓██    ╠╠▒▒▐█▀▀▌`░╫██           ███████▒▒▒▒░▒▒½█████╬╬╣███
                                                                ███ ,█▄ ╠▒▒▒╫▌,▄▀,▒╫██           ╟██████▒▒▒░╣⌠▒▓█████╬╬╣██▌
                                                               ╘██µ ██` ╠▒▒░██╬φ╠▄▓██`            ██████░░▌φ╠░▓█████▓╬╬▓██
                                                                ╟██  .φ╠▒░▄█▀░░▄██▀└              █████▌▒╣φ▒░▓██████╬╬╣██
                                                                 ▀██▄▄▄╓▄███████▀                ▐█████░▓φ▒▄███████▓╬╣██
                                                                   ╙▀▀▀██▀└                      ████▓▄▀φ▄▓████████╬▓█▀
                                                                                                ▓███╬╩╔╣██████████▓██└
                                                                                              ╓████▀▄▓████████▀████▀
                                                                                            ,▓███████████████─]██╙
                                                                                         ,▄▓██████████████▀└  ╙
                                                                                    ,╓▄▓███████████████▀╙
                                                                             `"▀▀▀████████▀▀▀▀`▄███▀▀└
                                                                                              └└
                
                
                
                                    11\   11\                     11\             11\   11\            11\                                       11\
                                  1111 |  \__|                    11 |            111\  11 |           11 |                                      11 |
                                  \_11 |  11\ 1111111\   1111111\ 1111111\        1111\ 11 | 111111\ 111111\   11\  11\  11\  111111\   111111\  11 |  11\
                                    11 |  11 |11  __11\ 11  _____|11  __11\       11 11\11 |11  __11\\_11  _|  11 | 11 | 11 |11  __11\ 11  __11\ 11 | 11  |
                                    11 |  11 |11 |  11 |11 /      11 |  11 |      11 \1111 |11111111 | 11 |    11 | 11 | 11 |11 /  11 |11 |  \__|111111  /
                                    11 |  11 |11 |  11 |11 |      11 |  11 |      11 |\111 |11   ____| 11 |11\ 11 | 11 | 11 |11 |  11 |11 |      11  _11<
                                  111111\ 11 |11 |  11 |\1111111\ 11 |  11 |      11 | \11 |\1111111\  \1111  |\11111\1111  |\111111  |11 |      11 | \11\
                                  \______|\__|\__|  \__| \_______|\__|  \__|      \__|  \__| \_______|  \____/  \_____\____/  \______/ \__|      \__|  \__|
                
                
                
                                               111111\                                                               11\     11\
                                              11  __11\                                                              11 |    \__|
                                              11 /  11 | 111111\   111111\   111111\   111111\   111111\   111111\ 111111\   11\  111111\  1111111\
                                              11111111 |11  __11\ 11  __11\ 11  __11\ 11  __11\ 11  __11\  \____11\\_11  _|  11 |11  __11\ 11  __11\
                                              11  __11 |11 /  11 |11 /  11 |11 |  \__|11111111 |11 /  11 | 1111111 | 11 |    11 |11 /  11 |11 |  11 |
                                              11 |  11 |11 |  11 |11 |  11 |11 |      11   ____|11 |  11 |11  __11 | 11 |11\ 11 |11 |  11 |11 |  11 |
                                              11 |  11 |\1111111 |\1111111 |11 |      \1111111\ \1111111 |\1111111 | \1111  |11 |\111111  |11 |  11 |
                                              \__|  \__| \____11 | \____11 |\__|       \_______| \____11 | \_______|  \____/ \__| \______/ \__|  \__|
                                                        11\   11 |11\   11 |                    11\   11 |
                                                        \111111  |\111111  |                    \111111  |
                                                         \______/  \______/                      \______/
                                                                1111111\                        11\
                                                                11  __11\                       11 |
                                                                11 |  11 | 111111\  11\   11\ 111111\    111111\   111111\
                                                                1111111  |11  __11\ 11 |  11 |\_11  _|  11  __11\ 11  __11\
                                                                11  __11< 11 /  11 |11 |  11 |  11 |    11111111 |11 |  \__|
                                                                11 |  11 |11 |  11 |11 |  11 |  11 |11\ 11   ____|11 |
                                                                11 |  11 |\111111  |\111111  |  \1111  |\1111111\ 11 |
                                                                \__|  \__| \______/  \______/    \____/  \_______|\__|
                */
                
                // SPDX-License-Identifier: MIT
                
                // File contracts/interfaces/IClipperExchangeInterface.sol
                
                
                pragma solidity 0.8.17;
                
                /// @title Clipper interface subset used in swaps
                interface IClipperExchangeInterface {
                    struct Signature {
                        uint8 v;
                        bytes32 r;
                        bytes32 s;
                    }
                
                    function sellEthForToken(address outputToken, uint256 inputAmount, uint256 outputAmount, uint256 goodUntil, address destinationAddress, Signature calldata theSignature, bytes calldata auxiliaryData) external payable;
                    function sellTokenForEth(address inputToken, uint256 inputAmount, uint256 outputAmount, uint256 goodUntil, address destinationAddress, Signature calldata theSignature, bytes calldata auxiliaryData) external;
                    function swap(address inputToken, address outputToken, uint256 inputAmount, uint256 outputAmount, uint256 goodUntil, address destinationAddress, Signature calldata theSignature, bytes calldata auxiliaryData) external;
                }
                
                
                // File contracts/helpers/RouterErrors.sol
                
                
                pragma solidity 0.8.17;
                
                library RouterErrors {
                    error ReturnAmountIsNotEnough();
                    error InvalidMsgValue();
                    error ERC20TransferFailed();
                }
                
                
                // File @1inch/solidity-utils/contracts/[email protected]
                
                
                pragma solidity ^0.8.0;
                
                abstract contract EthReceiver {
                    error EthDepositRejected();
                
                    receive() external payable {
                        _receive();
                    }
                
                    function _receive() internal virtual {
                        // solhint-disable-next-line avoid-tx-origin
                        if (msg.sender == tx.origin) revert EthDepositRejected();
                    }
                }
                
                
                // File @openzeppelin/contracts/token/ERC20/[email protected]
                
                // OpenZeppelin Contracts (last updated v4.6.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);
                }
                
                
                // File @1inch/solidity-utils/contracts/interfaces/[email protected]
                
                
                pragma solidity ^0.8.0;
                
                
                interface IDaiLikePermit {
                    function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;
                }
                
                
                // File @1inch/solidity-utils/contracts/libraries/[email protected]
                
                
                pragma solidity ^0.8.0;
                
                library RevertReasonForwarder {
                    function reRevert() internal pure {
                        // bubble up revert reason from latest external call
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                            returndatacopy(ptr, 0, returndatasize())
                            revert(ptr, returndatasize())
                        }
                    }
                }
                
                
                // File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
                
                // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-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);
                }
                
                
                // File @1inch/solidity-utils/contracts/libraries/[email protected]
                
                
                pragma solidity ^0.8.0;
                
                
                
                
                library SafeERC20 {
                    error SafeTransferFailed();
                    error SafeTransferFromFailed();
                    error ForceApproveFailed();
                    error SafeIncreaseAllowanceFailed();
                    error SafeDecreaseAllowanceFailed();
                    error SafePermitBadLength();
                
                    // Ensures method do not revert or return boolean `true`, admits call to non-smart-contract
                    function safeTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
                        bytes4 selector = token.transferFrom.selector;
                        bool success;
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let data := mload(0x40)
                
                            mstore(data, selector)
                            mstore(add(data, 0x04), from)
                            mstore(add(data, 0x24), to)
                            mstore(add(data, 0x44), amount)
                            success := call(gas(), token, 0, data, 100, 0x0, 0x20)
                            if success {
                                switch returndatasize()
                                case 0 { success := gt(extcodesize(token), 0) }
                                default { success := and(gt(returndatasize(), 31), eq(mload(0), 1)) }
                            }
                        }
                        if (!success) revert SafeTransferFromFailed();
                    }
                
                    // Ensures method do not revert or return boolean `true`, admits call to non-smart-contract
                    function safeTransfer(IERC20 token, address to, uint256 value) internal {
                        if (!_makeCall(token, token.transfer.selector, to, value)) {
                            revert SafeTransferFailed();
                        }
                    }
                
                    // If `approve(from, to, amount)` fails, try to `approve(from, to, 0)` before retry
                    function forceApprove(IERC20 token, address spender, uint256 value) internal {
                        if (!_makeCall(token, token.approve.selector, spender, value)) {
                            if (!_makeCall(token, token.approve.selector, spender, 0) ||
                                !_makeCall(token, token.approve.selector, spender, value))
                            {
                                revert ForceApproveFailed();
                            }
                        }
                    }
                
                    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                        uint256 allowance = token.allowance(address(this), spender);
                        if (value > type(uint256).max - allowance) revert SafeIncreaseAllowanceFailed();
                        forceApprove(token, spender, allowance + value);
                    }
                
                    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                        uint256 allowance = token.allowance(address(this), spender);
                        if (value > allowance) revert SafeDecreaseAllowanceFailed();
                        forceApprove(token, spender, allowance - value);
                    }
                
                    function safePermit(IERC20 token, bytes calldata permit) internal {
                        bool success;
                        if (permit.length == 32 * 7) {
                            success = _makeCalldataCall(token, IERC20Permit.permit.selector, permit);
                        } else if (permit.length == 32 * 8) {
                            success = _makeCalldataCall(token, IDaiLikePermit.permit.selector, permit);
                        } else {
                            revert SafePermitBadLength();
                        }
                        if (!success) RevertReasonForwarder.reRevert();
                    }
                
                    function _makeCall(IERC20 token, bytes4 selector, address to, uint256 amount) private returns(bool success) {
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let data := mload(0x40)
                
                            mstore(data, selector)
                            mstore(add(data, 0x04), to)
                            mstore(add(data, 0x24), amount)
                            success := call(gas(), token, 0, data, 0x44, 0x0, 0x20)
                            if success {
                                switch returndatasize()
                                case 0 { success := gt(extcodesize(token), 0) }
                                default { success := and(gt(returndatasize(), 31), eq(mload(0), 1)) }
                            }
                        }
                    }
                
                    function _makeCalldataCall(IERC20 token, bytes4 selector, bytes calldata args) private returns(bool success) {
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let len := add(4, args.length)
                            let data := mload(0x40)
                
                            mstore(data, selector)
                            calldatacopy(add(data, 0x04), args.offset, args.length)
                            success := call(gas(), token, 0, data, len, 0x0, 0x20)
                            if success {
                                switch returndatasize()
                                case 0 { success := gt(extcodesize(token), 0) }
                                default { success := and(gt(returndatasize(), 31), eq(mload(0), 1)) }
                            }
                        }
                    }
                }
                
                
                // File @1inch/solidity-utils/contracts/interfaces/[email protected]
                
                
                pragma solidity ^0.8.0;
                
                interface IWETH is IERC20 {
                    function deposit() external payable;
                    function withdraw(uint256 amount) external;
                }
                
                
                // File contracts/routers/ClipperRouter.sol
                
                
                pragma solidity 0.8.17;
                
                
                
                
                
                
                /// @title Clipper router that allows to use `ClipperExchangeInterface` for swaps
                contract ClipperRouter is EthReceiver {
                    using SafeERC20 for IERC20;
                
                    uint256 private constant _SIGNATURE_S_MASK = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
                    uint256 private constant _SIGNATURE_V_SHIFT = 255;
                    bytes6 private constant _INCH_TAG_WITH_LENGTH_PREFIX = "\x051INCH";
                    IERC20 private constant _ETH = IERC20(address(0));
                    IWETH private immutable _WETH;  // solhint-disable-line var-name-mixedcase
                
                    constructor(IWETH weth) {
                        _WETH = weth;
                    }
                
                    /// @notice Same as `clipperSwapTo` but calls permit first,
                    /// allowing to approve token spending and make a swap in one transaction.
                    /// @dev See tests for examples
                    /// @param recipient Address that will receive swap funds
                    /// @param srcToken Source token
                    /// @param dstToken Destination token
                    /// @param inputAmount Amount of source tokens to swap
                    /// @param outputAmount Amount of destination tokens to receive
                    /// @param goodUntil Timestamp until the swap will be valid
                    /// @param r Clipper order signature (r part)
                    /// @param vs Clipper order signature (vs part)
                    /// @param permit Should contain valid permit that can be used in `IERC20Permit.permit` calls.
                    /// @return returnAmount Amount of destination tokens received
                    function clipperSwapToWithPermit(
                        IClipperExchangeInterface clipperExchange,
                        address payable recipient,
                        IERC20 srcToken,
                        IERC20 dstToken,
                        uint256 inputAmount,
                        uint256 outputAmount,
                        uint256 goodUntil,
                        bytes32 r,
                        bytes32 vs,
                        bytes calldata permit
                    ) external returns(uint256 returnAmount) {
                        srcToken.safePermit(permit);
                        return clipperSwapTo(clipperExchange, recipient, srcToken, dstToken, inputAmount, outputAmount, goodUntil, r, vs);
                    }
                
                    /// @notice Same as `clipperSwapTo` but uses `msg.sender` as recipient
                    /// @param srcToken Source token
                    /// @param dstToken Destination token
                    /// @param inputAmount Amount of source tokens to swap
                    /// @param outputAmount Amount of destination tokens to receive
                    /// @param goodUntil Timestamp until the swap will be valid
                    /// @param r Clipper order signature (r part)
                    /// @param vs Clipper order signature (vs part)
                    /// @return returnAmount Amount of destination tokens received
                    function clipperSwap(
                        IClipperExchangeInterface clipperExchange,
                        IERC20 srcToken,
                        IERC20 dstToken,
                        uint256 inputAmount,
                        uint256 outputAmount,
                        uint256 goodUntil,
                        bytes32 r,
                        bytes32 vs
                    ) external payable returns(uint256 returnAmount) {
                        return clipperSwapTo(clipperExchange, payable(msg.sender), srcToken, dstToken, inputAmount, outputAmount, goodUntil, r, vs);
                    }
                
                    /// @notice Performs swap using Clipper exchange. Wraps and unwraps ETH if required.
                    /// Sending non-zero `msg.value` for anything but ETH swaps is prohibited
                    /// @param recipient Address that will receive swap funds
                    /// @param srcToken Source token
                    /// @param dstToken Destination token
                    /// @param inputAmount Amount of source tokens to swap
                    /// @param outputAmount Amount of destination tokens to receive
                    /// @param goodUntil Timestamp until the swap will be valid
                    /// @param r Clipper order signature (r part)
                    /// @param vs Clipper order signature (vs part)
                    /// @return returnAmount Amount of destination tokens received
                    function clipperSwapTo(
                        IClipperExchangeInterface clipperExchange,
                        address payable recipient,
                        IERC20 srcToken,
                        IERC20 dstToken,
                        uint256 inputAmount,
                        uint256 outputAmount,
                        uint256 goodUntil,
                        bytes32 r,
                        bytes32 vs
                    ) public payable returns(uint256 returnAmount) {
                        bool srcETH = srcToken == _ETH;
                        if (srcETH) {
                            if (msg.value != inputAmount) revert RouterErrors.InvalidMsgValue();
                        } else if (srcToken == _WETH) {
                            srcETH = true;
                            if (msg.value != 0) revert RouterErrors.InvalidMsgValue();
                            // _WETH.transferFrom(msg.sender, address(this), inputAmount);
                            // _WETH.withdraw(inputAmount);
                            address weth = address(_WETH);
                            bytes4 transferFromSelector = _WETH.transferFrom.selector;
                            bytes4 withdrawSelector = _WETH.withdraw.selector;
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let ptr := mload(0x40)
                
                                mstore(ptr, transferFromSelector)
                                mstore(add(ptr, 0x04), caller())
                                mstore(add(ptr, 0x24), address())
                                mstore(add(ptr, 0x44), inputAmount)
                                if iszero(call(gas(), weth, 0, ptr, 0x64, 0, 0)) {
                                    returndatacopy(ptr, 0, returndatasize())
                                    revert(ptr, returndatasize())
                                }
                
                                mstore(ptr, withdrawSelector)
                                mstore(add(ptr, 0x04), inputAmount)
                                if iszero(call(gas(), weth, 0, ptr, 0x24, 0, 0)) {
                                    returndatacopy(ptr, 0, returndatasize())
                                    revert(ptr, returndatasize())
                                }
                            }
                        } else {
                            if (msg.value != 0) revert RouterErrors.InvalidMsgValue();
                            srcToken.safeTransferFrom(msg.sender, address(clipperExchange), inputAmount);
                        }
                
                        if (srcETH) {
                            // clipperExchange.sellEthForToken{value: inputAmount}(address(dstToken), inputAmount, outputAmount, goodUntil, recipient, signature, _INCH_TAG);
                            address clipper = address(clipperExchange);
                            bytes4 selector = clipperExchange.sellEthForToken.selector;
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let ptr := mload(0x40)
                
                                mstore(ptr, selector)
                                mstore(add(ptr, 0x04), dstToken)
                                mstore(add(ptr, 0x24), inputAmount)
                                mstore(add(ptr, 0x44), outputAmount)
                                mstore(add(ptr, 0x64), goodUntil)
                                mstore(add(ptr, 0x84), recipient)
                                mstore(add(ptr, 0xa4), add(27, shr(_SIGNATURE_V_SHIFT, vs)))
                                mstore(add(ptr, 0xc4), r)
                                mstore(add(ptr, 0xe4), and(vs, _SIGNATURE_S_MASK))
                                mstore(add(ptr, 0x104), 0x120)
                                mstore(add(ptr, 0x143), _INCH_TAG_WITH_LENGTH_PREFIX)
                                if iszero(call(gas(), clipper, inputAmount, ptr, 0x149, 0, 0)) {
                                    returndatacopy(ptr, 0, returndatasize())
                                    revert(ptr, returndatasize())
                                }
                            }
                        } else if (dstToken == _ETH || dstToken == _WETH) {
                            // clipperExchange.sellTokenForEth(address(srcToken), inputAmount, outputAmount, goodUntil, recipient, signature, _INCH_TAG);
                            address clipper = address(clipperExchange);
                            bytes4 selector = clipperExchange.sellTokenForEth.selector;
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let ptr := mload(0x40)
                
                                mstore(ptr, selector)
                                mstore(add(ptr, 0x04), srcToken)
                                mstore(add(ptr, 0x24), inputAmount)
                                mstore(add(ptr, 0x44), outputAmount)
                                mstore(add(ptr, 0x64), goodUntil)
                                switch iszero(dstToken)
                                case 1 {
                                    mstore(add(ptr, 0x84), recipient)
                                }
                                default {
                                    mstore(add(ptr, 0x84), address())
                                }
                                mstore(add(ptr, 0xa4), add(27, shr(_SIGNATURE_V_SHIFT, vs)))
                                mstore(add(ptr, 0xc4), r)
                                mstore(add(ptr, 0xe4), and(vs, _SIGNATURE_S_MASK))
                                mstore(add(ptr, 0x104), 0x120)
                                mstore(add(ptr, 0x143), _INCH_TAG_WITH_LENGTH_PREFIX)
                                if iszero(call(gas(), clipper, 0, ptr, 0x149, 0, 0)) {
                                    returndatacopy(ptr, 0, returndatasize())
                                    revert(ptr, returndatasize())
                                }
                            }
                
                            if (dstToken == _WETH) {
                                // _WETH.deposit{value: outputAmount}();
                                // _WETH.transfer(recipient, outputAmount);
                                address weth = address(_WETH);
                                bytes4 depositSelector = _WETH.deposit.selector;
                                bytes4 transferSelector = _WETH.transfer.selector;
                                /// @solidity memory-safe-assembly
                                assembly { // solhint-disable-line no-inline-assembly
                                    let ptr := mload(0x40)
                
                                    mstore(ptr, depositSelector)
                                    if iszero(call(gas(), weth, outputAmount, ptr, 0x04, 0, 0)) {
                                        returndatacopy(ptr, 0, returndatasize())
                                        revert(ptr, returndatasize())
                                    }
                
                                    mstore(ptr, transferSelector)
                                    mstore(add(ptr, 0x04), recipient)
                                    mstore(add(ptr, 0x24), outputAmount)
                                    if iszero(call(gas(), weth, 0, ptr, 0x44, 0, 0)) {
                                        returndatacopy(ptr, 0, returndatasize())
                                        revert(ptr, returndatasize())
                                    }
                                }
                            }
                        } else {
                            // clipperExchange.swap(address(srcToken), address(dstToken), inputAmount, outputAmount, goodUntil, recipient, signature, _INCH_TAG);
                            address clipper = address(clipperExchange);
                            bytes4 selector = clipperExchange.swap.selector;
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let ptr := mload(0x40)
                
                                mstore(ptr, selector)
                                mstore(add(ptr, 0x04), srcToken)
                                mstore(add(ptr, 0x24), dstToken)
                                mstore(add(ptr, 0x44), inputAmount)
                                mstore(add(ptr, 0x64), outputAmount)
                                mstore(add(ptr, 0x84), goodUntil)
                                mstore(add(ptr, 0xa4), recipient)
                                mstore(add(ptr, 0xc4), add(27, shr(_SIGNATURE_V_SHIFT, vs)))
                                mstore(add(ptr, 0xe4), r)
                                mstore(add(ptr, 0x104), and(vs, _SIGNATURE_S_MASK))
                                mstore(add(ptr, 0x124), 0x140)
                                mstore(add(ptr, 0x163), _INCH_TAG_WITH_LENGTH_PREFIX)
                                if iszero(call(gas(), clipper, 0, ptr, 0x169, 0, 0)) {
                                    returndatacopy(ptr, 0, returndatasize())
                                    revert(ptr, returndatasize())
                                }
                            }
                        }
                
                        return outputAmount;
                    }
                }
                
                
                // File contracts/interfaces/IAggregationExecutor.sol
                
                
                pragma solidity 0.8.17;
                
                /// @title Interface for making arbitrary calls during swap
                interface IAggregationExecutor {
                    /// @notice propagates information about original msg.sender and executes arbitrary data
                    function execute(address msgSender) external payable;  // 0x4b64e492
                }
                
                
                // File @1inch/solidity-utils/contracts/interfaces/[email protected]
                
                
                pragma solidity ^0.8.0;
                
                
                interface IERC20MetadataUppercase {
                    function NAME() external view returns (string memory);  // solhint-disable-line func-name-mixedcase
                    function SYMBOL() external view returns (string memory);  // solhint-disable-line func-name-mixedcase
                }
                
                
                // File @1inch/solidity-utils/contracts/libraries/[email protected]
                
                
                pragma solidity ^0.8.0;
                
                /// @title Library with gas-efficient string operations
                library StringUtil {
                    function toHex(uint256 value) internal pure returns (string memory) {
                        return toHex(abi.encodePacked(value));
                    }
                
                    function toHex(address value) internal pure returns (string memory) {
                        return toHex(abi.encodePacked(value));
                    }
                
                    function toHex(bytes memory data) internal pure returns (string memory result) {
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            function _toHex16(input) -> output {
                                output := or(
                                    and(input, 0xFFFFFFFFFFFFFFFF000000000000000000000000000000000000000000000000),
                                    shr(64, and(input, 0x0000000000000000FFFFFFFFFFFFFFFF00000000000000000000000000000000))
                                )
                                output := or(
                                    and(output, 0xFFFFFFFF000000000000000000000000FFFFFFFF000000000000000000000000),
                                    shr(32, and(output, 0x00000000FFFFFFFF000000000000000000000000FFFFFFFF0000000000000000))
                                )
                                output := or(
                                    and(output, 0xFFFF000000000000FFFF000000000000FFFF000000000000FFFF000000000000),
                                    shr(16, and(output, 0x0000FFFF000000000000FFFF000000000000FFFF000000000000FFFF00000000))
                                )
                                output := or(
                                    and(output, 0xFF000000FF000000FF000000FF000000FF000000FF000000FF000000FF000000),
                                    shr(8, and(output, 0x00FF000000FF000000FF000000FF000000FF000000FF000000FF000000FF0000))
                                )
                                output := or(
                                    shr(4, and(output, 0xF000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000)),
                                    shr(8, and(output, 0x0F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F00))
                                )
                                output := add(
                                    add(0x3030303030303030303030303030303030303030303030303030303030303030, output),
                                    mul(
                                        and(
                                            shr(4, add(output, 0x0606060606060606060606060606060606060606060606060606060606060606)),
                                            0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F
                                        ),
                                        7   // Change 7 to 39 for lower case output
                                    )
                                )
                            }
                
                            result := mload(0x40)
                            let length := mload(data)
                            let resultLength := shl(1, length)
                            let toPtr := add(result, 0x22)          // 32 bytes for length + 2 bytes for '0x'
                            mstore(0x40, add(toPtr, resultLength))  // move free memory pointer
                            mstore(add(result, 2), 0x3078)          // 0x3078 is right aligned so we write to `result + 2`
                                                                    // to store the last 2 bytes in the beginning of the string
                            mstore(result, add(resultLength, 2))    // extra 2 bytes for '0x'
                
                            for {
                                let fromPtr := add(data, 0x20)
                                let endPtr := add(fromPtr, length)
                            } lt(fromPtr, endPtr) {
                                fromPtr := add(fromPtr, 0x20)
                            } {
                                let rawData := mload(fromPtr)
                                let hexData := _toHex16(rawData)
                                mstore(toPtr, hexData)
                                toPtr := add(toPtr, 0x20)
                                hexData := _toHex16(shl(128, rawData))
                                mstore(toPtr, hexData)
                                toPtr := add(toPtr, 0x20)
                            }
                        }
                    }
                }
                
                
                // File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
                
                // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
                
                pragma solidity ^0.8.0;
                
                /**
                 * @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);
                }
                
                
                // File @1inch/solidity-utils/contracts/libraries/[email protected]
                
                
                pragma solidity ^0.8.0;
                
                
                
                
                
                library UniERC20 {
                    using SafeERC20 for IERC20;
                
                    error InsufficientBalance();
                    error ApproveCalledOnETH();
                    error NotEnoughValue();
                    error FromIsNotSender();
                    error ToIsNotThis();
                    error ETHTransferFailed();
                
                    uint256 private constant _RAW_CALL_GAS_LIMIT = 5000;
                    IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
                    IERC20 private constant _ZERO_ADDRESS = IERC20(address(0));
                
                    function isETH(IERC20 token) internal pure returns (bool) {
                        return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS);
                    }
                
                    function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) {
                        if (isETH(token)) {
                            return account.balance;
                        } else {
                            return token.balanceOf(account);
                        }
                    }
                
                    /// @dev note that this function does nothing in case of zero amount
                    function uniTransfer(IERC20 token, address payable to, uint256 amount) internal {
                        if (amount > 0) {
                            if (isETH(token)) {
                                if (address(this).balance < amount) revert InsufficientBalance();
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, ) = to.call{value: amount, gas: _RAW_CALL_GAS_LIMIT}("");
                                if (!success) revert ETHTransferFailed();
                            } else {
                                token.safeTransfer(to, amount);
                            }
                        }
                    }
                
                    /// @dev note that this function does nothing in case of zero amount
                    function uniTransferFrom(IERC20 token, address payable from, address to, uint256 amount) internal {
                        if (amount > 0) {
                            if (isETH(token)) {
                                if (msg.value < amount) revert NotEnoughValue();
                                if (from != msg.sender) revert FromIsNotSender();
                                if (to != address(this)) revert ToIsNotThis();
                                if (msg.value > amount) {
                                    // Return remainder if exist
                                    unchecked {
                                        // solhint-disable-next-line avoid-low-level-calls
                                        (bool success, ) = from.call{value: msg.value - amount, gas: _RAW_CALL_GAS_LIMIT}("");
                                        if (!success) revert ETHTransferFailed();
                                    }
                                }
                            } else {
                                token.safeTransferFrom(from, to, amount);
                            }
                        }
                    }
                
                    function uniSymbol(IERC20 token) internal view returns(string memory) {
                        return _uniDecode(token, IERC20Metadata.symbol.selector, IERC20MetadataUppercase.SYMBOL.selector);
                    }
                
                    function uniName(IERC20 token) internal view returns(string memory) {
                        return _uniDecode(token, IERC20Metadata.name.selector, IERC20MetadataUppercase.NAME.selector);
                    }
                
                    function uniApprove(IERC20 token, address to, uint256 amount) internal {
                        if (isETH(token)) revert ApproveCalledOnETH();
                
                        token.forceApprove(to, amount);
                    }
                
                    /// 20K gas is provided to account for possible implementations of name/symbol
                    /// (token implementation might be behind proxy or store the value in storage)
                    function _uniDecode(IERC20 token, bytes4 lowerCaseSelector, bytes4 upperCaseSelector) private view returns(string memory result) {
                        if (isETH(token)) {
                            return "ETH";
                        }
                
                        (bool success, bytes memory data) = address(token).staticcall{ gas: 20000 }(
                            abi.encodeWithSelector(lowerCaseSelector)
                        );
                        if (!success) {
                            (success, data) = address(token).staticcall{ gas: 20000 }(
                                abi.encodeWithSelector(upperCaseSelector)
                            );
                        }
                
                        if (success && data.length >= 0x40) {
                            (uint256 offset, uint256 len) = abi.decode(data, (uint256, uint256));
                            if (offset == 0x20 && len > 0 && data.length == 0x40 + len) {
                                /// @solidity memory-safe-assembly
                                assembly { // solhint-disable-line no-inline-assembly
                                    result := add(data, 0x20)
                                }
                                return result;
                            }
                        }
                
                        if (success && data.length == 32) {
                            uint256 len = 0;
                            while (len < data.length && data[len] >= 0x20 && data[len] <= 0x7E) {
                                unchecked {
                                    len++;
                                }
                            }
                
                            if (len > 0) {
                                /// @solidity memory-safe-assembly
                                assembly { // solhint-disable-line no-inline-assembly
                                    mstore(data, len)
                                }
                                return string(data);
                            }
                        }
                
                        return StringUtil.toHex(address(token));
                    }
                }
                
                
                // File contracts/routers/GenericRouter.sol
                
                
                pragma solidity 0.8.17;
                
                
                
                
                
                contract GenericRouter is EthReceiver {
                    using UniERC20 for IERC20;
                    using SafeERC20 for IERC20;
                
                    error ZeroMinReturn();
                    error ZeroReturnAmount();
                
                    uint256 private constant _PARTIAL_FILL = 1 << 0;
                    uint256 private constant _REQUIRES_EXTRA_ETH = 1 << 1;
                
                    struct SwapDescription {
                        IERC20 srcToken;
                        IERC20 dstToken;
                        address payable srcReceiver;
                        address payable dstReceiver;
                        uint256 amount;
                        uint256 minReturnAmount;
                        uint256 flags;
                    }
                
                    /// @notice Performs a swap, delegating all calls encoded in `data` to `executor`. See tests for usage examples
                    /// @dev router keeps 1 wei of every token on the contract balance for gas optimisations reasons. This affects first swap of every token by leaving 1 wei on the contract.
                    /// @param executor Aggregation executor that executes calls described in `data`
                    /// @param desc Swap description
                    /// @param permit Should contain valid permit that can be used in `IERC20Permit.permit` calls.
                    /// @param data Encoded calls that `caller` should execute in between of swaps
                    /// @return returnAmount Resulting token amount
                    /// @return spentAmount Source token amount
                    function swap(
                        IAggregationExecutor executor,
                        SwapDescription calldata desc,
                        bytes calldata permit,
                        bytes calldata data
                    )
                        external
                        payable
                        returns (
                            uint256 returnAmount,
                            uint256 spentAmount
                        )
                    {
                        if (desc.minReturnAmount == 0) revert ZeroMinReturn();
                
                        IERC20 srcToken = desc.srcToken;
                        IERC20 dstToken = desc.dstToken;
                
                        bool srcETH = srcToken.isETH();
                        if (desc.flags & _REQUIRES_EXTRA_ETH != 0) {
                            if (msg.value <= (srcETH ? desc.amount : 0)) revert RouterErrors.InvalidMsgValue();
                        } else {
                            if (msg.value != (srcETH ? desc.amount : 0)) revert RouterErrors.InvalidMsgValue();
                        }
                
                        if (!srcETH) {
                            if (permit.length > 0) {
                                srcToken.safePermit(permit);
                            }
                            srcToken.safeTransferFrom(msg.sender, desc.srcReceiver, desc.amount);
                        }
                
                        _execute(executor, msg.sender, desc.amount, data);
                
                        spentAmount = desc.amount;
                        // we leave 1 wei on the router for gas optimisations reasons
                        returnAmount = dstToken.uniBalanceOf(address(this));
                        if (returnAmount == 0) revert ZeroReturnAmount();
                        unchecked { returnAmount--; }
                
                        if (desc.flags & _PARTIAL_FILL != 0) {
                            uint256 unspentAmount = srcToken.uniBalanceOf(address(this));
                            if (unspentAmount > 1) {
                                // we leave 1 wei on the router for gas optimisations reasons
                                unchecked { unspentAmount--; }
                                spentAmount -= unspentAmount;
                                srcToken.uniTransfer(payable(msg.sender), unspentAmount);
                            }
                            if (returnAmount * desc.amount < desc.minReturnAmount * spentAmount) revert RouterErrors.ReturnAmountIsNotEnough();
                        } else {
                            if (returnAmount < desc.minReturnAmount) revert RouterErrors.ReturnAmountIsNotEnough();
                        }
                
                        address payable dstReceiver = (desc.dstReceiver == address(0)) ? payable(msg.sender) : desc.dstReceiver;
                        dstToken.uniTransfer(dstReceiver, returnAmount);
                    }
                
                    function _execute(
                        IAggregationExecutor executor,
                        address srcTokenOwner,
                        uint256 inputAmount,
                        bytes calldata data
                    ) private {
                        bytes4 executeSelector = executor.execute.selector;
                        /// @solidity memory-safe-assembly
                        assembly {  // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                
                            mstore(ptr, executeSelector)
                            mstore(add(ptr, 0x04), srcTokenOwner)
                            calldatacopy(add(ptr, 0x24), data.offset, data.length)
                            mstore(add(add(ptr, 0x24), data.length), inputAmount)
                
                            if iszero(call(gas(), executor, callvalue(), ptr, add(0x44, data.length), 0, 0)) {
                                returndatacopy(ptr, 0, returndatasize())
                                revert(ptr, returndatasize())
                            }
                        }
                    }
                }
                
                
                // File contracts/routers/UnoswapRouter.sol
                
                
                pragma solidity 0.8.17;
                
                
                
                
                contract UnoswapRouter is EthReceiver {
                    using SafeERC20 for IERC20;
                
                    error ReservesCallFailed();
                    error SwapAmountTooLarge();
                
                    bytes4 private constant _TRANSFER_FROM_CALL_SELECTOR = 0x23b872dd;
                    bytes4 private constant _WETH_DEPOSIT_CALL_SELECTOR = 0xd0e30db0;
                    bytes4 private constant _WETH_WITHDRAW_CALL_SELECTOR = 0x2e1a7d4d;
                    bytes4 private constant _ERC20_TRANSFER_CALL_SELECTOR = 0xa9059cbb;
                    uint256 private constant _ADDRESS_MASK =   0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff;
                    uint256 private constant _REVERSE_MASK =   0x8000000000000000000000000000000000000000000000000000000000000000;
                    uint256 private constant _WETH_MASK =      0x4000000000000000000000000000000000000000000000000000000000000000;
                    uint256 private constant _NUMERATOR_MASK = 0x0000000000000000ffffffff0000000000000000000000000000000000000000;
                    /// @dev WETH address is network-specific and needs to be changed before deployment.
                    /// It can not be moved to immutable as immutables are not supported in assembly
                    address private constant _WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
                    bytes4 private constant _UNISWAP_PAIR_RESERVES_CALL_SELECTOR = 0x0902f1ac;
                    bytes4 private constant _UNISWAP_PAIR_SWAP_CALL_SELECTOR = 0x022c0d9f;
                    uint256 private constant _DENOMINATOR = 1e9;
                    uint256 private constant _NUMERATOR_OFFSET = 160;
                    uint256 private constant _MAX_SWAP_AMOUNT = (1 << 112) - 1;  // type(uint112).max;
                
                    /// @notice Same as `unoswapTo` but calls permit first,
                    /// allowing to approve token spending and make a swap in one transaction.
                    /// @param recipient Address that will receive swapped funds
                    /// @param srcToken Source token
                    /// @param amount Amount of source tokens to swap
                    /// @param minReturn Minimal allowed returnAmount to make transaction commit
                    /// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
                    /// @param permit Should contain valid permit that can be used in `IERC20Permit.permit` calls.
                    /// See tests for examples
                    function unoswapToWithPermit(
                        address payable recipient,
                        IERC20 srcToken,
                        uint256 amount,
                        uint256 minReturn,
                        uint256[] calldata pools,
                        bytes calldata permit
                    ) external returns(uint256 returnAmount) {
                        srcToken.safePermit(permit);
                        return _unoswap(recipient, srcToken, amount, minReturn, pools);
                    }
                
                    /// @notice Performs swap using Uniswap exchange. Wraps and unwraps ETH if required.
                    /// Sending non-zero `msg.value` for anything but ETH swaps is prohibited
                    /// @param recipient Address that will receive swapped funds
                    /// @param srcToken Source token
                    /// @param amount Amount of source tokens to swap
                    /// @param minReturn Minimal allowed returnAmount to make transaction commit
                    /// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
                    function unoswapTo(
                        address payable recipient,
                        IERC20 srcToken,
                        uint256 amount,
                        uint256 minReturn,
                        uint256[] calldata pools
                    ) external payable returns(uint256 returnAmount) {
                        return _unoswap(recipient, srcToken, amount, minReturn, pools);
                    }
                
                    /// @notice Performs swap using Uniswap exchange. Wraps and unwraps ETH if required.
                    /// Sending non-zero `msg.value` for anything but ETH swaps is prohibited
                    /// @param srcToken Source token
                    /// @param amount Amount of source tokens to swap
                    /// @param minReturn Minimal allowed returnAmount to make transaction commit
                    /// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
                    function unoswap(
                        IERC20 srcToken,
                        uint256 amount,
                        uint256 minReturn,
                        uint256[] calldata pools
                    ) external payable returns(uint256 returnAmount) {
                        return _unoswap(payable(msg.sender), srcToken, amount, minReturn, pools);
                    }
                
                    function _unoswap(
                        address payable recipient,
                        IERC20 srcToken,
                        uint256 amount,
                        uint256 minReturn,
                        uint256[] calldata pools
                    ) private returns(uint256 returnAmount) {
                        assembly {  // solhint-disable-line no-inline-assembly
                            function reRevert() {
                                returndatacopy(0, 0, returndatasize())
                                revert(0, returndatasize())
                            }
                
                            function validateERC20Transfer(status) {
                                if iszero(status) {
                                    reRevert()
                                }
                                let success := or(
                                    iszero(returndatasize()),                       // empty return data
                                    and(gt(returndatasize(), 31), eq(mload(0), 1))  // true in return data
                                )
                                if iszero(success) {
                                    mstore(0, 0xf27f64e400000000000000000000000000000000000000000000000000000000)  // ERC20TransferFailed()
                                    revert(0, 4)
                                }
                            }
                
                            function swap(emptyPtr, swapAmount, pair, reversed, numerator, to) -> ret {
                                mstore(emptyPtr, _UNISWAP_PAIR_RESERVES_CALL_SELECTOR)
                                if iszero(staticcall(gas(), pair, emptyPtr, 0x4, emptyPtr, 0x40)) {
                                    reRevert()
                                }
                                if iszero(eq(returndatasize(), 0x60)) {
                                    mstore(0, 0x85cd58dc00000000000000000000000000000000000000000000000000000000)  // ReservesCallFailed()
                                    revert(0, 4)
                                }
                
                                let reserve0 := mload(emptyPtr)
                                let reserve1 := mload(add(emptyPtr, 0x20))
                                if reversed {
                                    let tmp := reserve0
                                    reserve0 := reserve1
                                    reserve1 := tmp
                                }
                                // this will not overflow as reserve0, reserve1 and ret fit to 112 bit and numerator and _DENOMINATOR fit to 32 bit
                                ret := mul(swapAmount, numerator)
                                ret := div(mul(ret, reserve1), add(ret, mul(reserve0, _DENOMINATOR)))
                
                                mstore(emptyPtr, _UNISWAP_PAIR_SWAP_CALL_SELECTOR)
                                reversed := iszero(reversed)
                                mstore(add(emptyPtr, 0x04), mul(ret, iszero(reversed)))
                                mstore(add(emptyPtr, 0x24), mul(ret, reversed))
                                mstore(add(emptyPtr, 0x44), to)
                                mstore(add(emptyPtr, 0x64), 0x80)
                                mstore(add(emptyPtr, 0x84), 0)
                                if iszero(call(gas(), pair, 0, emptyPtr, 0xa4, 0, 0)) {
                                    reRevert()
                                }
                            }
                
                            // make sure that input amount fits in 112 bit
                            if gt(amount, _MAX_SWAP_AMOUNT) {
                                mstore(0, 0xcf0b4d3a00000000000000000000000000000000000000000000000000000000)  // SwapAmountTooLarge()
                                revert(0, 4)
                            }
                
                            let emptyPtr := mload(0x40)
                            mstore(0x40, add(emptyPtr, 0xc0))
                
                            let poolsEndOffset := add(pools.offset, shl(5, pools.length))
                            let rawPair := calldataload(pools.offset)
                            switch srcToken
                            case 0 {
                                if iszero(eq(amount, callvalue())) {
                                    mstore(0, 0x1841b4e100000000000000000000000000000000000000000000000000000000)  // InvalidMsgValue()
                                    revert(0, 4)
                                }
                
                                mstore(emptyPtr, _WETH_DEPOSIT_CALL_SELECTOR)
                                if iszero(call(gas(), _WETH, amount, emptyPtr, 0x4, 0, 0)) {
                                    reRevert()
                                }
                
                                mstore(emptyPtr, _ERC20_TRANSFER_CALL_SELECTOR)
                                mstore(add(emptyPtr, 0x4), and(rawPair, _ADDRESS_MASK))
                                mstore(add(emptyPtr, 0x24), amount)
                                if iszero(call(gas(), _WETH, 0, emptyPtr, 0x44, 0, 0)) {
                                    reRevert()
                                }
                            }
                            default {
                                if callvalue() {
                                    mstore(0, 0x1841b4e100000000000000000000000000000000000000000000000000000000)  // InvalidMsgValue()
                                    revert(0, 4)
                                }
                
                                mstore(emptyPtr, _TRANSFER_FROM_CALL_SELECTOR)
                                mstore(add(emptyPtr, 0x4), caller())
                                mstore(add(emptyPtr, 0x24), and(rawPair, _ADDRESS_MASK))
                                mstore(add(emptyPtr, 0x44), amount)
                                validateERC20Transfer(
                                    call(gas(), srcToken, 0, emptyPtr, 0x64, 0, 0x20)
                                )
                            }
                
                            returnAmount := amount
                
                            for {let i := add(pools.offset, 0x20)} lt(i, poolsEndOffset) {i := add(i, 0x20)} {
                                let nextRawPair := calldataload(i)
                
                                returnAmount := swap(
                                    emptyPtr,
                                    returnAmount,
                                    and(rawPair, _ADDRESS_MASK),
                                    and(rawPair, _REVERSE_MASK),
                                    shr(_NUMERATOR_OFFSET, and(rawPair, _NUMERATOR_MASK)),
                                    and(nextRawPair, _ADDRESS_MASK)
                                )
                
                                rawPair := nextRawPair
                            }
                
                            switch and(rawPair, _WETH_MASK)
                            case 0 {
                                returnAmount := swap(
                                    emptyPtr,
                                    returnAmount,
                                    and(rawPair, _ADDRESS_MASK),
                                    and(rawPair, _REVERSE_MASK),
                                    shr(_NUMERATOR_OFFSET, and(rawPair, _NUMERATOR_MASK)),
                                    recipient
                                )
                            }
                            default {
                                returnAmount := swap(
                                    emptyPtr,
                                    returnAmount,
                                    and(rawPair, _ADDRESS_MASK),
                                    and(rawPair, _REVERSE_MASK),
                                    shr(_NUMERATOR_OFFSET, and(rawPair, _NUMERATOR_MASK)),
                                    address()
                                )
                
                                mstore(emptyPtr, _WETH_WITHDRAW_CALL_SELECTOR)
                                mstore(add(emptyPtr, 0x04), returnAmount)
                                if iszero(call(gas(), _WETH, 0, emptyPtr, 0x24, 0, 0)) {
                                    reRevert()
                                }
                
                                if iszero(call(gas(), recipient, returnAmount, 0, 0, 0, 0)) {
                                    reRevert()
                                }
                            }
                        }
                        if (returnAmount < minReturn) revert RouterErrors.ReturnAmountIsNotEnough();
                    }
                }
                
                
                // File contracts/interfaces/IUniswapV3Pool.sol
                
                pragma solidity 0.8.17;
                
                interface IUniswapV3Pool {
                    /// @notice Swap token0 for token1, or token1 for token0
                    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
                    /// @param recipient The address to receive the output of the swap
                    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
                    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
                    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
                    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
                    /// @param data Any data to be passed through to the callback
                    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
                    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
                    function swap(
                        address recipient,
                        bool zeroForOne,
                        int256 amountSpecified,
                        uint160 sqrtPriceLimitX96,
                        bytes calldata data
                    ) external returns (int256 amount0, int256 amount1);
                
                    /// @notice The first of the two tokens of the pool, sorted by address
                    /// @return The token contract address
                    function token0() external view returns (address);
                
                    /// @notice The second of the two tokens of the pool, sorted by address
                    /// @return The token contract address
                    function token1() external view returns (address);
                
                    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
                    /// @return The fee
                    function fee() external view returns (uint24);
                }
                
                
                // File contracts/interfaces/IUniswapV3SwapCallback.sol
                
                pragma solidity 0.8.17;
                
                /// @title Callback for IUniswapV3PoolActions#swap
                /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
                interface IUniswapV3SwapCallback {
                    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
                    /// @dev In the implementation you must pay the pool tokens owed for the swap.
                    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
                    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
                    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
                    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
                    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
                    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
                    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
                    function uniswapV3SwapCallback(
                        int256 amount0Delta,
                        int256 amount1Delta,
                        bytes calldata data
                    ) external;
                }
                
                
                // File @openzeppelin/contracts/utils/[email protected]
                
                // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
                
                pragma solidity ^0.8.1;
                
                /**
                 * @dev Collection of functions related to the address type
                 */
                library Address {
                    /**
                     * @dev Returns true if `account` is a contract.
                     *
                     * [IMPORTANT]
                     * ====
                     * It is unsafe to assume that an address for which this function returns
                     * false is an externally-owned account (EOA) and not a contract.
                     *
                     * Among others, `isContract` will return false for the following
                     * types of addresses:
                     *
                     *  - an externally-owned account
                     *  - a contract in construction
                     *  - an address where a contract will be created
                     *  - an address where a contract lived, but was destroyed
                     * ====
                     *
                     * [IMPORTANT]
                     * ====
                     * You shouldn't rely on `isContract` to protect against flash loan attacks!
                     *
                     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                     * constructor.
                     * ====
                     */
                    function isContract(address account) internal view returns (bool) {
                        // This method relies on extcodesize/address.code.length, which returns 0
                        // for contracts in construction, since the code is only stored at the end
                        // of the constructor execution.
                
                        return account.code.length > 0;
                    }
                
                    /**
                     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                     * `recipient`, forwarding all available gas and reverting on errors.
                     *
                     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                     * of certain opcodes, possibly making contracts go over the 2300 gas limit
                     * imposed by `transfer`, making them unable to receive funds via
                     * `transfer`. {sendValue} removes this limitation.
                     *
                     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                     *
                     * IMPORTANT: because control is transferred to `recipient`, care must be
                     * taken to not create reentrancy vulnerabilities. Consider using
                     * {ReentrancyGuard} or the
                     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                     */
                    function sendValue(address payable recipient, uint256 amount) internal {
                        require(address(this).balance >= amount, "Address: insufficient balance");
                
                        (bool success, ) = recipient.call{value: amount}("");
                        require(success, "Address: unable to send value, recipient may have reverted");
                    }
                
                    /**
                     * @dev Performs a Solidity function call using a low level `call`. A
                     * plain `call` is an unsafe replacement for a function call: use this
                     * function instead.
                     *
                     * If `target` reverts with a revert reason, it is bubbled up by this
                     * function (like regular Solidity function calls).
                     *
                     * Returns the raw returned data. To convert to the expected return value,
                     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                     *
                     * Requirements:
                     *
                     * - `target` must be a contract.
                     * - calling `target` with `data` must not revert.
                     *
                     * _Available since v3.1._
                     */
                    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                        return functionCall(target, data, "Address: low-level call failed");
                    }
                
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                     * `errorMessage` as a fallback revert reason when `target` reverts.
                     *
                     * _Available since v3.1._
                     */
                    function functionCall(
                        address target,
                        bytes memory data,
                        string memory errorMessage
                    ) internal returns (bytes memory) {
                        return functionCallWithValue(target, data, 0, errorMessage);
                    }
                
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                     * but also transferring `value` wei to `target`.
                     *
                     * Requirements:
                     *
                     * - the calling contract must have an ETH balance of at least `value`.
                     * - the called Solidity function must be `payable`.
                     *
                     * _Available since v3.1._
                     */
                    function functionCallWithValue(
                        address target,
                        bytes memory data,
                        uint256 value
                    ) internal returns (bytes memory) {
                        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                    }
                
                    /**
                     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                     * with `errorMessage` as a fallback revert reason when `target` reverts.
                     *
                     * _Available since v3.1._
                     */
                    function functionCallWithValue(
                        address target,
                        bytes memory data,
                        uint256 value,
                        string memory errorMessage
                    ) internal returns (bytes memory) {
                        require(address(this).balance >= value, "Address: insufficient balance for call");
                        require(isContract(target), "Address: call to non-contract");
                
                        (bool success, bytes memory returndata) = target.call{value: value}(data);
                        return verifyCallResult(success, returndata, errorMessage);
                    }
                
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                     * but performing a static call.
                     *
                     * _Available since v3.3._
                     */
                    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                        return functionStaticCall(target, data, "Address: low-level static call failed");
                    }
                
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                     * but performing a static call.
                     *
                     * _Available since v3.3._
                     */
                    function functionStaticCall(
                        address target,
                        bytes memory data,
                        string memory errorMessage
                    ) internal view returns (bytes memory) {
                        require(isContract(target), "Address: static call to non-contract");
                
                        (bool success, bytes memory returndata) = target.staticcall(data);
                        return verifyCallResult(success, returndata, errorMessage);
                    }
                
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                     * but performing a delegate call.
                     *
                     * _Available since v3.4._
                     */
                    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                    }
                
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                     * but performing a delegate call.
                     *
                     * _Available since v3.4._
                     */
                    function functionDelegateCall(
                        address target,
                        bytes memory data,
                        string memory errorMessage
                    ) internal returns (bytes memory) {
                        require(isContract(target), "Address: delegate call to non-contract");
                
                        (bool success, bytes memory returndata) = target.delegatecall(data);
                        return verifyCallResult(success, returndata, errorMessage);
                    }
                
                    /**
                     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
                     * revert reason using the provided one.
                     *
                     * _Available since v4.3._
                     */
                    function verifyCallResult(
                        bool success,
                        bytes memory returndata,
                        string memory errorMessage
                    ) internal pure returns (bytes memory) {
                        if (success) {
                            return returndata;
                        } else {
                            // Look for revert reason and bubble it up if present
                            if (returndata.length > 0) {
                                // The easiest way to bubble the revert reason is using memory via assembly
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let returndata_size := mload(returndata)
                                    revert(add(32, returndata), returndata_size)
                                }
                            } else {
                                revert(errorMessage);
                            }
                        }
                    }
                }
                
                
                // File @openzeppelin/contracts/utils/math/[email protected]
                
                // OpenZeppelin Contracts (last updated v4.7.0) (utils/math/SafeCast.sol)
                
                pragma solidity ^0.8.0;
                
                /**
                 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
                 * checks.
                 *
                 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
                 * easily result in undesired exploitation or bugs, since developers usually
                 * assume that overflows raise errors. `SafeCast` restores this intuition by
                 * reverting the transaction when such an operation overflows.
                 *
                 * Using this library instead of the unchecked operations eliminates an entire
                 * class of bugs, so it's recommended to use it always.
                 *
                 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
                 * all math on `uint256` and `int256` and then downcasting.
                 */
                library SafeCast {
                    /**
                     * @dev Returns the downcasted uint248 from uint256, reverting on
                     * overflow (when the input is greater than largest uint248).
                     *
                     * Counterpart to Solidity's `uint248` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 248 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint248(uint256 value) internal pure returns (uint248) {
                        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
                        return uint248(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint240 from uint256, reverting on
                     * overflow (when the input is greater than largest uint240).
                     *
                     * Counterpart to Solidity's `uint240` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 240 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint240(uint256 value) internal pure returns (uint240) {
                        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
                        return uint240(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint232 from uint256, reverting on
                     * overflow (when the input is greater than largest uint232).
                     *
                     * Counterpart to Solidity's `uint232` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 232 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint232(uint256 value) internal pure returns (uint232) {
                        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
                        return uint232(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint224 from uint256, reverting on
                     * overflow (when the input is greater than largest uint224).
                     *
                     * Counterpart to Solidity's `uint224` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 224 bits
                     *
                     * _Available since v4.2._
                     */
                    function toUint224(uint256 value) internal pure returns (uint224) {
                        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
                        return uint224(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint216 from uint256, reverting on
                     * overflow (when the input is greater than largest uint216).
                     *
                     * Counterpart to Solidity's `uint216` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 216 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint216(uint256 value) internal pure returns (uint216) {
                        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
                        return uint216(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint208 from uint256, reverting on
                     * overflow (when the input is greater than largest uint208).
                     *
                     * Counterpart to Solidity's `uint208` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 208 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint208(uint256 value) internal pure returns (uint208) {
                        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
                        return uint208(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint200 from uint256, reverting on
                     * overflow (when the input is greater than largest uint200).
                     *
                     * Counterpart to Solidity's `uint200` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 200 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint200(uint256 value) internal pure returns (uint200) {
                        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
                        return uint200(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint192 from uint256, reverting on
                     * overflow (when the input is greater than largest uint192).
                     *
                     * Counterpart to Solidity's `uint192` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 192 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint192(uint256 value) internal pure returns (uint192) {
                        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
                        return uint192(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint184 from uint256, reverting on
                     * overflow (when the input is greater than largest uint184).
                     *
                     * Counterpart to Solidity's `uint184` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 184 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint184(uint256 value) internal pure returns (uint184) {
                        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
                        return uint184(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint176 from uint256, reverting on
                     * overflow (when the input is greater than largest uint176).
                     *
                     * Counterpart to Solidity's `uint176` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 176 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint176(uint256 value) internal pure returns (uint176) {
                        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
                        return uint176(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint168 from uint256, reverting on
                     * overflow (when the input is greater than largest uint168).
                     *
                     * Counterpart to Solidity's `uint168` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 168 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint168(uint256 value) internal pure returns (uint168) {
                        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
                        return uint168(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint160 from uint256, reverting on
                     * overflow (when the input is greater than largest uint160).
                     *
                     * Counterpart to Solidity's `uint160` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 160 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint160(uint256 value) internal pure returns (uint160) {
                        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
                        return uint160(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint152 from uint256, reverting on
                     * overflow (when the input is greater than largest uint152).
                     *
                     * Counterpart to Solidity's `uint152` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 152 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint152(uint256 value) internal pure returns (uint152) {
                        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
                        return uint152(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint144 from uint256, reverting on
                     * overflow (when the input is greater than largest uint144).
                     *
                     * Counterpart to Solidity's `uint144` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 144 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint144(uint256 value) internal pure returns (uint144) {
                        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
                        return uint144(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint136 from uint256, reverting on
                     * overflow (when the input is greater than largest uint136).
                     *
                     * Counterpart to Solidity's `uint136` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 136 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint136(uint256 value) internal pure returns (uint136) {
                        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
                        return uint136(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint128 from uint256, reverting on
                     * overflow (when the input is greater than largest uint128).
                     *
                     * Counterpart to Solidity's `uint128` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 128 bits
                     *
                     * _Available since v2.5._
                     */
                    function toUint128(uint256 value) internal pure returns (uint128) {
                        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
                        return uint128(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint120 from uint256, reverting on
                     * overflow (when the input is greater than largest uint120).
                     *
                     * Counterpart to Solidity's `uint120` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 120 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint120(uint256 value) internal pure returns (uint120) {
                        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
                        return uint120(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint112 from uint256, reverting on
                     * overflow (when the input is greater than largest uint112).
                     *
                     * Counterpart to Solidity's `uint112` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 112 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint112(uint256 value) internal pure returns (uint112) {
                        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
                        return uint112(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint104 from uint256, reverting on
                     * overflow (when the input is greater than largest uint104).
                     *
                     * Counterpart to Solidity's `uint104` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 104 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint104(uint256 value) internal pure returns (uint104) {
                        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
                        return uint104(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint96 from uint256, reverting on
                     * overflow (when the input is greater than largest uint96).
                     *
                     * Counterpart to Solidity's `uint96` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 96 bits
                     *
                     * _Available since v4.2._
                     */
                    function toUint96(uint256 value) internal pure returns (uint96) {
                        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
                        return uint96(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint88 from uint256, reverting on
                     * overflow (when the input is greater than largest uint88).
                     *
                     * Counterpart to Solidity's `uint88` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 88 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint88(uint256 value) internal pure returns (uint88) {
                        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
                        return uint88(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint80 from uint256, reverting on
                     * overflow (when the input is greater than largest uint80).
                     *
                     * Counterpart to Solidity's `uint80` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 80 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint80(uint256 value) internal pure returns (uint80) {
                        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
                        return uint80(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint72 from uint256, reverting on
                     * overflow (when the input is greater than largest uint72).
                     *
                     * Counterpart to Solidity's `uint72` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 72 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint72(uint256 value) internal pure returns (uint72) {
                        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
                        return uint72(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint64 from uint256, reverting on
                     * overflow (when the input is greater than largest uint64).
                     *
                     * Counterpart to Solidity's `uint64` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 64 bits
                     *
                     * _Available since v2.5._
                     */
                    function toUint64(uint256 value) internal pure returns (uint64) {
                        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
                        return uint64(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint56 from uint256, reverting on
                     * overflow (when the input is greater than largest uint56).
                     *
                     * Counterpart to Solidity's `uint56` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 56 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint56(uint256 value) internal pure returns (uint56) {
                        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
                        return uint56(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint48 from uint256, reverting on
                     * overflow (when the input is greater than largest uint48).
                     *
                     * Counterpart to Solidity's `uint48` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 48 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint48(uint256 value) internal pure returns (uint48) {
                        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
                        return uint48(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint40 from uint256, reverting on
                     * overflow (when the input is greater than largest uint40).
                     *
                     * Counterpart to Solidity's `uint40` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 40 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint40(uint256 value) internal pure returns (uint40) {
                        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
                        return uint40(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint32 from uint256, reverting on
                     * overflow (when the input is greater than largest uint32).
                     *
                     * Counterpart to Solidity's `uint32` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 32 bits
                     *
                     * _Available since v2.5._
                     */
                    function toUint32(uint256 value) internal pure returns (uint32) {
                        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
                        return uint32(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint24 from uint256, reverting on
                     * overflow (when the input is greater than largest uint24).
                     *
                     * Counterpart to Solidity's `uint24` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 24 bits
                     *
                     * _Available since v4.7._
                     */
                    function toUint24(uint256 value) internal pure returns (uint24) {
                        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
                        return uint24(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint16 from uint256, reverting on
                     * overflow (when the input is greater than largest uint16).
                     *
                     * Counterpart to Solidity's `uint16` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 16 bits
                     *
                     * _Available since v2.5._
                     */
                    function toUint16(uint256 value) internal pure returns (uint16) {
                        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
                        return uint16(value);
                    }
                
                    /**
                     * @dev Returns the downcasted uint8 from uint256, reverting on
                     * overflow (when the input is greater than largest uint8).
                     *
                     * Counterpart to Solidity's `uint8` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 8 bits
                     *
                     * _Available since v2.5._
                     */
                    function toUint8(uint256 value) internal pure returns (uint8) {
                        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
                        return uint8(value);
                    }
                
                    /**
                     * @dev Converts a signed int256 into an unsigned uint256.
                     *
                     * Requirements:
                     *
                     * - input must be greater than or equal to 0.
                     *
                     * _Available since v3.0._
                     */
                    function toUint256(int256 value) internal pure returns (uint256) {
                        require(value >= 0, "SafeCast: value must be positive");
                        return uint256(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int248 from int256, reverting on
                     * overflow (when the input is less than smallest int248 or
                     * greater than largest int248).
                     *
                     * Counterpart to Solidity's `int248` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 248 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt248(int256 value) internal pure returns (int248) {
                        require(value >= type(int248).min && value <= type(int248).max, "SafeCast: value doesn't fit in 248 bits");
                        return int248(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int240 from int256, reverting on
                     * overflow (when the input is less than smallest int240 or
                     * greater than largest int240).
                     *
                     * Counterpart to Solidity's `int240` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 240 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt240(int256 value) internal pure returns (int240) {
                        require(value >= type(int240).min && value <= type(int240).max, "SafeCast: value doesn't fit in 240 bits");
                        return int240(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int232 from int256, reverting on
                     * overflow (when the input is less than smallest int232 or
                     * greater than largest int232).
                     *
                     * Counterpart to Solidity's `int232` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 232 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt232(int256 value) internal pure returns (int232) {
                        require(value >= type(int232).min && value <= type(int232).max, "SafeCast: value doesn't fit in 232 bits");
                        return int232(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int224 from int256, reverting on
                     * overflow (when the input is less than smallest int224 or
                     * greater than largest int224).
                     *
                     * Counterpart to Solidity's `int224` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 224 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt224(int256 value) internal pure returns (int224) {
                        require(value >= type(int224).min && value <= type(int224).max, "SafeCast: value doesn't fit in 224 bits");
                        return int224(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int216 from int256, reverting on
                     * overflow (when the input is less than smallest int216 or
                     * greater than largest int216).
                     *
                     * Counterpart to Solidity's `int216` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 216 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt216(int256 value) internal pure returns (int216) {
                        require(value >= type(int216).min && value <= type(int216).max, "SafeCast: value doesn't fit in 216 bits");
                        return int216(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int208 from int256, reverting on
                     * overflow (when the input is less than smallest int208 or
                     * greater than largest int208).
                     *
                     * Counterpart to Solidity's `int208` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 208 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt208(int256 value) internal pure returns (int208) {
                        require(value >= type(int208).min && value <= type(int208).max, "SafeCast: value doesn't fit in 208 bits");
                        return int208(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int200 from int256, reverting on
                     * overflow (when the input is less than smallest int200 or
                     * greater than largest int200).
                     *
                     * Counterpart to Solidity's `int200` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 200 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt200(int256 value) internal pure returns (int200) {
                        require(value >= type(int200).min && value <= type(int200).max, "SafeCast: value doesn't fit in 200 bits");
                        return int200(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int192 from int256, reverting on
                     * overflow (when the input is less than smallest int192 or
                     * greater than largest int192).
                     *
                     * Counterpart to Solidity's `int192` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 192 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt192(int256 value) internal pure returns (int192) {
                        require(value >= type(int192).min && value <= type(int192).max, "SafeCast: value doesn't fit in 192 bits");
                        return int192(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int184 from int256, reverting on
                     * overflow (when the input is less than smallest int184 or
                     * greater than largest int184).
                     *
                     * Counterpart to Solidity's `int184` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 184 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt184(int256 value) internal pure returns (int184) {
                        require(value >= type(int184).min && value <= type(int184).max, "SafeCast: value doesn't fit in 184 bits");
                        return int184(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int176 from int256, reverting on
                     * overflow (when the input is less than smallest int176 or
                     * greater than largest int176).
                     *
                     * Counterpart to Solidity's `int176` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 176 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt176(int256 value) internal pure returns (int176) {
                        require(value >= type(int176).min && value <= type(int176).max, "SafeCast: value doesn't fit in 176 bits");
                        return int176(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int168 from int256, reverting on
                     * overflow (when the input is less than smallest int168 or
                     * greater than largest int168).
                     *
                     * Counterpart to Solidity's `int168` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 168 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt168(int256 value) internal pure returns (int168) {
                        require(value >= type(int168).min && value <= type(int168).max, "SafeCast: value doesn't fit in 168 bits");
                        return int168(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int160 from int256, reverting on
                     * overflow (when the input is less than smallest int160 or
                     * greater than largest int160).
                     *
                     * Counterpart to Solidity's `int160` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 160 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt160(int256 value) internal pure returns (int160) {
                        require(value >= type(int160).min && value <= type(int160).max, "SafeCast: value doesn't fit in 160 bits");
                        return int160(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int152 from int256, reverting on
                     * overflow (when the input is less than smallest int152 or
                     * greater than largest int152).
                     *
                     * Counterpart to Solidity's `int152` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 152 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt152(int256 value) internal pure returns (int152) {
                        require(value >= type(int152).min && value <= type(int152).max, "SafeCast: value doesn't fit in 152 bits");
                        return int152(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int144 from int256, reverting on
                     * overflow (when the input is less than smallest int144 or
                     * greater than largest int144).
                     *
                     * Counterpart to Solidity's `int144` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 144 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt144(int256 value) internal pure returns (int144) {
                        require(value >= type(int144).min && value <= type(int144).max, "SafeCast: value doesn't fit in 144 bits");
                        return int144(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int136 from int256, reverting on
                     * overflow (when the input is less than smallest int136 or
                     * greater than largest int136).
                     *
                     * Counterpart to Solidity's `int136` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 136 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt136(int256 value) internal pure returns (int136) {
                        require(value >= type(int136).min && value <= type(int136).max, "SafeCast: value doesn't fit in 136 bits");
                        return int136(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int128 from int256, reverting on
                     * overflow (when the input is less than smallest int128 or
                     * greater than largest int128).
                     *
                     * Counterpart to Solidity's `int128` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 128 bits
                     *
                     * _Available since v3.1._
                     */
                    function toInt128(int256 value) internal pure returns (int128) {
                        require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
                        return int128(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int120 from int256, reverting on
                     * overflow (when the input is less than smallest int120 or
                     * greater than largest int120).
                     *
                     * Counterpart to Solidity's `int120` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 120 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt120(int256 value) internal pure returns (int120) {
                        require(value >= type(int120).min && value <= type(int120).max, "SafeCast: value doesn't fit in 120 bits");
                        return int120(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int112 from int256, reverting on
                     * overflow (when the input is less than smallest int112 or
                     * greater than largest int112).
                     *
                     * Counterpart to Solidity's `int112` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 112 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt112(int256 value) internal pure returns (int112) {
                        require(value >= type(int112).min && value <= type(int112).max, "SafeCast: value doesn't fit in 112 bits");
                        return int112(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int104 from int256, reverting on
                     * overflow (when the input is less than smallest int104 or
                     * greater than largest int104).
                     *
                     * Counterpart to Solidity's `int104` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 104 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt104(int256 value) internal pure returns (int104) {
                        require(value >= type(int104).min && value <= type(int104).max, "SafeCast: value doesn't fit in 104 bits");
                        return int104(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int96 from int256, reverting on
                     * overflow (when the input is less than smallest int96 or
                     * greater than largest int96).
                     *
                     * Counterpart to Solidity's `int96` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 96 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt96(int256 value) internal pure returns (int96) {
                        require(value >= type(int96).min && value <= type(int96).max, "SafeCast: value doesn't fit in 96 bits");
                        return int96(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int88 from int256, reverting on
                     * overflow (when the input is less than smallest int88 or
                     * greater than largest int88).
                     *
                     * Counterpart to Solidity's `int88` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 88 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt88(int256 value) internal pure returns (int88) {
                        require(value >= type(int88).min && value <= type(int88).max, "SafeCast: value doesn't fit in 88 bits");
                        return int88(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int80 from int256, reverting on
                     * overflow (when the input is less than smallest int80 or
                     * greater than largest int80).
                     *
                     * Counterpart to Solidity's `int80` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 80 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt80(int256 value) internal pure returns (int80) {
                        require(value >= type(int80).min && value <= type(int80).max, "SafeCast: value doesn't fit in 80 bits");
                        return int80(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int72 from int256, reverting on
                     * overflow (when the input is less than smallest int72 or
                     * greater than largest int72).
                     *
                     * Counterpart to Solidity's `int72` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 72 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt72(int256 value) internal pure returns (int72) {
                        require(value >= type(int72).min && value <= type(int72).max, "SafeCast: value doesn't fit in 72 bits");
                        return int72(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int64 from int256, reverting on
                     * overflow (when the input is less than smallest int64 or
                     * greater than largest int64).
                     *
                     * Counterpart to Solidity's `int64` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 64 bits
                     *
                     * _Available since v3.1._
                     */
                    function toInt64(int256 value) internal pure returns (int64) {
                        require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
                        return int64(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int56 from int256, reverting on
                     * overflow (when the input is less than smallest int56 or
                     * greater than largest int56).
                     *
                     * Counterpart to Solidity's `int56` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 56 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt56(int256 value) internal pure returns (int56) {
                        require(value >= type(int56).min && value <= type(int56).max, "SafeCast: value doesn't fit in 56 bits");
                        return int56(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int48 from int256, reverting on
                     * overflow (when the input is less than smallest int48 or
                     * greater than largest int48).
                     *
                     * Counterpart to Solidity's `int48` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 48 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt48(int256 value) internal pure returns (int48) {
                        require(value >= type(int48).min && value <= type(int48).max, "SafeCast: value doesn't fit in 48 bits");
                        return int48(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int40 from int256, reverting on
                     * overflow (when the input is less than smallest int40 or
                     * greater than largest int40).
                     *
                     * Counterpart to Solidity's `int40` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 40 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt40(int256 value) internal pure returns (int40) {
                        require(value >= type(int40).min && value <= type(int40).max, "SafeCast: value doesn't fit in 40 bits");
                        return int40(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int32 from int256, reverting on
                     * overflow (when the input is less than smallest int32 or
                     * greater than largest int32).
                     *
                     * Counterpart to Solidity's `int32` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 32 bits
                     *
                     * _Available since v3.1._
                     */
                    function toInt32(int256 value) internal pure returns (int32) {
                        require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
                        return int32(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int24 from int256, reverting on
                     * overflow (when the input is less than smallest int24 or
                     * greater than largest int24).
                     *
                     * Counterpart to Solidity's `int24` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 24 bits
                     *
                     * _Available since v4.7._
                     */
                    function toInt24(int256 value) internal pure returns (int24) {
                        require(value >= type(int24).min && value <= type(int24).max, "SafeCast: value doesn't fit in 24 bits");
                        return int24(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int16 from int256, reverting on
                     * overflow (when the input is less than smallest int16 or
                     * greater than largest int16).
                     *
                     * Counterpart to Solidity's `int16` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 16 bits
                     *
                     * _Available since v3.1._
                     */
                    function toInt16(int256 value) internal pure returns (int16) {
                        require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
                        return int16(value);
                    }
                
                    /**
                     * @dev Returns the downcasted int8 from int256, reverting on
                     * overflow (when the input is less than smallest int8 or
                     * greater than largest int8).
                     *
                     * Counterpart to Solidity's `int8` operator.
                     *
                     * Requirements:
                     *
                     * - input must fit into 8 bits
                     *
                     * _Available since v3.1._
                     */
                    function toInt8(int256 value) internal pure returns (int8) {
                        require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
                        return int8(value);
                    }
                
                    /**
                     * @dev Converts an unsigned uint256 into a signed int256.
                     *
                     * Requirements:
                     *
                     * - input must be less than or equal to maxInt256.
                     *
                     * _Available since v3.0._
                     */
                    function toInt256(uint256 value) internal pure returns (int256) {
                        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
                        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
                        return int256(value);
                    }
                }
                
                
                // File contracts/routers/UnoswapV3Router.sol
                
                
                pragma solidity 0.8.17;
                
                
                
                
                
                
                
                
                
                contract UnoswapV3Router is EthReceiver, IUniswapV3SwapCallback {
                    using Address for address payable;
                    using SafeERC20 for IERC20;
                
                    error EmptyPools();
                    error BadPool();
                
                    uint256 private constant _ONE_FOR_ZERO_MASK = 1 << 255;
                    uint256 private constant _WETH_UNWRAP_MASK = 1 << 253;
                    bytes32 private constant _POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
                    bytes32 private constant _FF_FACTORY = 0xff1F98431c8aD98523631AE4a59f267346ea31F9840000000000000000000000;
                    // concatenation of token0(), token1() fee(), transfer() and transferFrom() selectors
                    bytes32 private constant _SELECTORS = 0x0dfe1681d21220a7ddca3f43a9059cbb23b872dd000000000000000000000000;
                    uint256 private constant _ADDRESS_MASK =   0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff;
                    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
                    uint160 private constant _MIN_SQRT_RATIO = 4295128739 + 1;
                    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
                    uint160 private constant _MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342 - 1;
                    IWETH private immutable _WETH;  // solhint-disable-line var-name-mixedcase
                
                    constructor(IWETH weth) {
                        _WETH = weth;
                    }
                
                    /// @notice Same as `uniswapV3SwapTo` but calls permit first,
                    /// allowing to approve token spending and make a swap in one transaction.
                    /// @param recipient Address that will receive swap funds
                    /// @param srcToken Source token
                    /// @param amount Amount of source tokens to swap
                    /// @param minReturn Minimal allowed returnAmount to make transaction commit
                    /// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
                    /// @param permit Should contain valid permit that can be used in `IERC20Permit.permit` calls.
                    /// See tests for examples
                    function uniswapV3SwapToWithPermit(
                        address payable recipient,
                        IERC20 srcToken,
                        uint256 amount,
                        uint256 minReturn,
                        uint256[] calldata pools,
                        bytes calldata permit
                    ) external returns(uint256 returnAmount) {
                        srcToken.safePermit(permit);
                        return _uniswapV3Swap(recipient, amount, minReturn, pools);
                    }
                
                    /// @notice Same as `uniswapV3SwapTo` but uses `msg.sender` as recipient
                    /// @param amount Amount of source tokens to swap
                    /// @param minReturn Minimal allowed returnAmount to make transaction commit
                    /// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
                    function uniswapV3Swap(
                        uint256 amount,
                        uint256 minReturn,
                        uint256[] calldata pools
                    ) external payable returns(uint256 returnAmount) {
                        return _uniswapV3Swap(payable(msg.sender), amount, minReturn, pools);
                    }
                
                    /// @notice Performs swap using Uniswap V3 exchange. Wraps and unwraps ETH if required.
                    /// Sending non-zero `msg.value` for anything but ETH swaps is prohibited
                    /// @param recipient Address that will receive swap funds
                    /// @param amount Amount of source tokens to swap
                    /// @param minReturn Minimal allowed returnAmount to make transaction commit
                    /// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
                    function uniswapV3SwapTo(
                        address payable recipient,
                        uint256 amount,
                        uint256 minReturn,
                        uint256[] calldata pools
                    ) external payable returns(uint256 returnAmount) {
                        return _uniswapV3Swap(recipient, amount, minReturn, pools);
                    }
                
                    function _uniswapV3Swap(
                        address payable recipient,
                        uint256 amount,
                        uint256 minReturn,
                        uint256[] calldata pools
                    ) private returns(uint256 returnAmount) {
                        unchecked {
                            uint256 len = pools.length;
                            if (len == 0) revert EmptyPools();
                            uint256 lastIndex = len - 1;
                            returnAmount = amount;
                            bool wrapWeth = msg.value > 0;
                            bool unwrapWeth = pools[lastIndex] & _WETH_UNWRAP_MASK > 0;
                            if (wrapWeth) {
                                if (msg.value != amount) revert RouterErrors.InvalidMsgValue();
                                _WETH.deposit{value: amount}();
                            }
                            if (len > 1) {
                                returnAmount = _makeSwap(address(this), wrapWeth ? address(this) : msg.sender, pools[0], returnAmount);
                
                                for (uint256 i = 1; i < lastIndex; i++) {
                                    returnAmount = _makeSwap(address(this), address(this), pools[i], returnAmount);
                                }
                                returnAmount = _makeSwap(unwrapWeth ? address(this) : recipient, address(this), pools[lastIndex], returnAmount);
                            } else {
                                returnAmount = _makeSwap(unwrapWeth ? address(this) : recipient, wrapWeth ? address(this) : msg.sender, pools[0], returnAmount);
                            }
                
                            if (returnAmount < minReturn) revert RouterErrors.ReturnAmountIsNotEnough();
                
                            if (unwrapWeth) {
                                _WETH.withdraw(returnAmount);
                                recipient.sendValue(returnAmount);
                            }
                        }
                    }
                
                    /// @inheritdoc IUniswapV3SwapCallback
                    function uniswapV3SwapCallback(
                        int256 amount0Delta,
                        int256 amount1Delta,
                        bytes calldata /* data */
                    ) external override {
                        assembly {  // solhint-disable-line no-inline-assembly
                            function reRevert() {
                                returndatacopy(0, 0, returndatasize())
                                revert(0, returndatasize())
                            }
                
                            function validateERC20Transfer(status) {
                                if iszero(status) {
                                    reRevert()
                                }
                                let success := or(
                                    iszero(returndatasize()),                       // empty return data
                                    and(gt(returndatasize(), 31), eq(mload(0), 1))  // true in return data
                                )
                                if iszero(success) {
                                    mstore(0, 0xf27f64e400000000000000000000000000000000000000000000000000000000)  // ERC20TransferFailed()
                                    revert(0, 4)
                                }
                            }
                
                            let emptyPtr := mload(0x40)
                            let resultPtr := add(emptyPtr, 0x15)  // 0x15 = _FF_FACTORY size
                
                            mstore(emptyPtr, _SELECTORS)
                            if iszero(staticcall(gas(), caller(), emptyPtr, 0x4, resultPtr, 0x20)) {
                                reRevert()
                            }
                            if iszero(staticcall(gas(), caller(), add(emptyPtr, 0x4), 0x4, add(resultPtr, 0x20), 0x20)) {
                                reRevert()
                            }
                            if iszero(staticcall(gas(), caller(), add(emptyPtr, 0x8), 0x4, add(resultPtr, 0x40), 0x20)) {
                                reRevert()
                            }
                
                            let token
                            let amount
                            switch sgt(amount0Delta, 0)
                            case 1 {
                                token := mload(resultPtr)
                                amount := amount0Delta
                            }
                            default {
                                token := mload(add(resultPtr, 0x20))
                                amount := amount1Delta
                            }
                
                            mstore(emptyPtr, _FF_FACTORY)
                            mstore(resultPtr, keccak256(resultPtr, 0x60)) // Compute the inner hash in-place
                            mstore(add(resultPtr, 0x20), _POOL_INIT_CODE_HASH)
                            let pool := and(keccak256(emptyPtr, 0x55), _ADDRESS_MASK)
                            if xor(pool, caller()) {
                                mstore(0, 0xb2c0272200000000000000000000000000000000000000000000000000000000)  // BadPool()
                                revert(0, 4)
                            }
                
                            let payer := calldataload(0x84)
                            mstore(emptyPtr, _SELECTORS)
                            switch eq(payer, address())
                            case 1 {
                                // token.safeTransfer(msg.sender,amount)
                                mstore(add(emptyPtr, 0x10), caller())
                                mstore(add(emptyPtr, 0x30), amount)
                                validateERC20Transfer(
                                    call(gas(), token, 0, add(emptyPtr, 0x0c), 0x44, 0, 0x20)
                                )
                            }
                            default {
                                // token.safeTransferFrom(payer, msg.sender, amount);
                                mstore(add(emptyPtr, 0x14), payer)
                                mstore(add(emptyPtr, 0x34), caller())
                                mstore(add(emptyPtr, 0x54), amount)
                                validateERC20Transfer(
                                    call(gas(), token, 0, add(emptyPtr, 0x10), 0x64, 0, 0x20)
                                )
                            }
                        }
                    }
                
                    function _makeSwap(address recipient, address payer, uint256 pool, uint256 amount) private returns (uint256) {
                        bool zeroForOne = pool & _ONE_FOR_ZERO_MASK == 0;
                        if (zeroForOne) {
                            (, int256 amount1) = IUniswapV3Pool(address(uint160(pool))).swap(
                                recipient,
                                zeroForOne,
                                SafeCast.toInt256(amount),
                                _MIN_SQRT_RATIO,
                                abi.encode(payer)
                            );
                            return SafeCast.toUint256(-amount1);
                        } else {
                            (int256 amount0,) = IUniswapV3Pool(address(uint160(pool))).swap(
                                recipient,
                                zeroForOne,
                                SafeCast.toInt256(amount),
                                _MAX_SQRT_RATIO,
                                abi.encode(payer)
                            );
                            return SafeCast.toUint256(-amount0);
                        }
                    }
                }
                
                
                // File @1inch/solidity-utils/contracts/[email protected]
                
                
                pragma solidity ^0.8.0;
                
                abstract contract OnlyWethReceiver is EthReceiver {
                    address private immutable _WETH;  // solhint-disable-line var-name-mixedcase
                
                    constructor(address weth) {
                        _WETH = address(weth);
                    }
                
                    function _receive() internal virtual override {
                        if (msg.sender != _WETH) revert EthDepositRejected();
                    }
                }
                
                
                // File @openzeppelin/contracts/interfaces/[email protected]
                
                // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
                
                pragma solidity ^0.8.0;
                
                /**
                 * @dev Interface of the ERC1271 standard signature validation method for
                 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
                 *
                 * _Available since v4.1._
                 */
                interface IERC1271 {
                    /**
                     * @dev Should return whether the signature provided is valid for the provided data
                     * @param hash      Hash of the data to be signed
                     * @param signature Signature byte array associated with _data
                     */
                    function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
                }
                
                
                // File @1inch/solidity-utils/contracts/libraries/[email protected]
                
                
                pragma solidity ^0.8.0;
                
                library ECDSA {
                    // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                    // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                    // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
                    // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                    //
                    // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                    // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                    // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                    // these malleable signatures as well.
                    uint256 private constant _S_BOUNDARY = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 + 1;
                    uint256 private constant _COMPACT_S_MASK = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
                    uint256 private constant _COMPACT_V_SHIFT = 255;
                
                    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal view returns(address signer) {
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            if lt(s, _S_BOUNDARY) {
                                let ptr := mload(0x40)
                
                                mstore(ptr, hash)
                                mstore(add(ptr, 0x20), v)
                                mstore(add(ptr, 0x40), r)
                                mstore(add(ptr, 0x60), s)
                                mstore(0, 0)
                                pop(staticcall(gas(), 0x1, ptr, 0x80, 0, 0x20))
                                signer := mload(0)
                            }
                        }
                    }
                
                    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal view returns(address signer) {
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let s := and(vs, _COMPACT_S_MASK)
                            if lt(s, _S_BOUNDARY) {
                                let ptr := mload(0x40)
                
                                mstore(ptr, hash)
                                mstore(add(ptr, 0x20), add(27, shr(_COMPACT_V_SHIFT, vs)))
                                mstore(add(ptr, 0x40), r)
                                mstore(add(ptr, 0x60), s)
                                mstore(0, 0)
                                pop(staticcall(gas(), 0x1, ptr, 0x80, 0, 0x20))
                                signer := mload(0)
                            }
                        }
                    }
                
                    /// WARNING!!!
                    /// There is a known signature malleability issue with two representations of signatures!
                    /// Even though this function is able to verify both standard 65-byte and compact 64-byte EIP-2098 signatures
                    /// one should never use raw signatures for any kind of invalidation logic in their code.
                    /// As the standard and compact representations are interchangeable any invalidation logic that relies on
                    /// signature uniqueness will get rekt.
                    /// More info: https://github.com/OpenZeppelin/openzeppelin-contracts/security/advisories/GHSA-4h98-2769-gh6h
                    function recover(bytes32 hash, bytes calldata signature) internal view returns(address signer) {
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                
                            // memory[ptr:ptr+0x80] = (hash, v, r, s)
                            switch signature.length
                            case 65 {
                                // memory[ptr+0x20:ptr+0x80] = (v, r, s)
                                mstore(add(ptr, 0x20), byte(0, calldataload(add(signature.offset, 0x40))))
                                calldatacopy(add(ptr, 0x40), signature.offset, 0x40)
                            }
                            case 64 {
                                // memory[ptr+0x20:ptr+0x80] = (v, r, s)
                                let vs := calldataload(add(signature.offset, 0x20))
                                mstore(add(ptr, 0x20), add(27, shr(_COMPACT_V_SHIFT, vs)))
                                calldatacopy(add(ptr, 0x40), signature.offset, 0x20)
                                mstore(add(ptr, 0x60), and(vs, _COMPACT_S_MASK))
                            }
                            default {
                                ptr := 0
                            }
                
                            if ptr {
                                if lt(mload(add(ptr, 0x60)), _S_BOUNDARY) {
                                    // memory[ptr:ptr+0x20] = (hash)
                                    mstore(ptr, hash)
                
                                    mstore(0, 0)
                                    pop(staticcall(gas(), 0x1, ptr, 0x80, 0, 0x20))
                                    signer := mload(0)
                                }
                            }
                        }
                    }
                
                    function recoverOrIsValidSignature(address signer, bytes32 hash, bytes calldata signature) internal view returns(bool success) {
                        if (signer == address(0)) return false;
                        if ((signature.length == 64 || signature.length == 65) && recover(hash, signature) == signer) {
                            return true;
                        }
                        return isValidSignature(signer, hash, signature);
                    }
                
                    function recoverOrIsValidSignature(address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal view returns(bool success) {
                        if (signer == address(0)) return false;
                        if (recover(hash, v, r, s) == signer) {
                            return true;
                        }
                        return isValidSignature(signer, hash, v, r, s);
                    }
                
                    function recoverOrIsValidSignature(address signer, bytes32 hash, bytes32 r, bytes32 vs) internal view returns(bool success) {
                        if (signer == address(0)) return false;
                        if (recover(hash, r, vs) == signer) {
                            return true;
                        }
                        return isValidSignature(signer, hash, r, vs);
                    }
                
                    function recoverOrIsValidSignature65(address signer, bytes32 hash, bytes32 r, bytes32 vs) internal view returns(bool success) {
                        if (signer == address(0)) return false;
                        if (recover(hash, r, vs) == signer) {
                            return true;
                        }
                        return isValidSignature65(signer, hash, r, vs);
                    }
                
                    function isValidSignature(address signer, bytes32 hash, bytes calldata signature) internal view returns(bool success) {
                        // (bool success, bytes memory data) = signer.staticcall(abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature));
                        // return success && data.length >= 4 && abi.decode(data, (bytes4)) == IERC1271.isValidSignature.selector;
                        bytes4 selector = IERC1271.isValidSignature.selector;
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                
                            mstore(ptr, selector)
                            mstore(add(ptr, 0x04), hash)
                            mstore(add(ptr, 0x24), 0x40)
                            mstore(add(ptr, 0x44), signature.length)
                            calldatacopy(add(ptr, 0x64), signature.offset, signature.length)
                            if staticcall(gas(), signer, ptr, add(0x64, signature.length), 0, 0x20) {
                                success := and(eq(selector, mload(0)), eq(returndatasize(), 0x20))
                            }
                        }
                    }
                
                    function isValidSignature(address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal view returns(bool success) {
                        bytes4 selector = IERC1271.isValidSignature.selector;
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                
                            mstore(ptr, selector)
                            mstore(add(ptr, 0x04), hash)
                            mstore(add(ptr, 0x24), 0x40)
                            mstore(add(ptr, 0x44), 65)
                            mstore(add(ptr, 0x64), r)
                            mstore(add(ptr, 0x84), s)
                            mstore8(add(ptr, 0xa4), v)
                            if staticcall(gas(), signer, ptr, 0xa5, 0, 0x20) {
                                success := and(eq(selector, mload(0)), eq(returndatasize(), 0x20))
                            }
                        }
                    }
                
                    function isValidSignature(address signer, bytes32 hash, bytes32 r, bytes32 vs) internal view returns(bool success) {
                        // (bool success, bytes memory data) = signer.staticcall(abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, abi.encodePacked(r, vs)));
                        // return success && data.length >= 4 && abi.decode(data, (bytes4)) == IERC1271.isValidSignature.selector;
                        bytes4 selector = IERC1271.isValidSignature.selector;
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                
                            mstore(ptr, selector)
                            mstore(add(ptr, 0x04), hash)
                            mstore(add(ptr, 0x24), 0x40)
                            mstore(add(ptr, 0x44), 64)
                            mstore(add(ptr, 0x64), r)
                            mstore(add(ptr, 0x84), vs)
                            if staticcall(gas(), signer, ptr, 0xa4, 0, 0x20) {
                                success := and(eq(selector, mload(0)), eq(returndatasize(), 0x20))
                            }
                        }
                    }
                
                    function isValidSignature65(address signer, bytes32 hash, bytes32 r, bytes32 vs) internal view returns(bool success) {
                        // (bool success, bytes memory data) = signer.staticcall(abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, abi.encodePacked(r, vs & ~uint256(1 << 255), uint8(vs >> 255))));
                        // return success && data.length >= 4 && abi.decode(data, (bytes4)) == IERC1271.isValidSignature.selector;
                        bytes4 selector = IERC1271.isValidSignature.selector;
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                
                            mstore(ptr, selector)
                            mstore(add(ptr, 0x04), hash)
                            mstore(add(ptr, 0x24), 0x40)
                            mstore(add(ptr, 0x44), 65)
                            mstore(add(ptr, 0x64), r)
                            mstore(add(ptr, 0x84), and(vs, _COMPACT_S_MASK))
                            mstore8(add(ptr, 0xa4), add(27, shr(_COMPACT_V_SHIFT, vs)))
                            if staticcall(gas(), signer, ptr, 0xa5, 0, 0x20) {
                                success := and(eq(selector, mload(0)), eq(returndatasize(), 0x20))
                            }
                        }
                    }
                
                    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 res) {
                        // 32 is the length in bytes of hash, enforced by the type signature above
                        // return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            mstore(0, 0x19457468657265756d205369676e6564204d6573736167653a0a333200000000) // "\x19Ethereum Signed Message:\n32"
                            mstore(28, hash)
                            res := keccak256(0, 60)
                        }
                    }
                
                    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 res) {
                        // return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                            mstore(ptr, 0x1901000000000000000000000000000000000000000000000000000000000000) // "\x19\x01"
                            mstore(add(ptr, 0x02), domainSeparator)
                            mstore(add(ptr, 0x22), structHash)
                            res := keccak256(ptr, 66)
                        }
                    }
                }
                
                
                // File @1inch/limit-order-protocol/contracts/[email protected]
                
                
                pragma solidity 0.8.17;
                
                library OrderRFQLib {
                    struct OrderRFQ {
                        uint256 info;  // lowest 64 bits is the order id, next 64 bits is the expiration timestamp
                        address makerAsset;
                        address takerAsset;
                        address maker;
                        address allowedSender;  // equals to Zero address on public orders
                        uint256 makingAmount;
                        uint256 takingAmount;
                    }
                
                    bytes32 constant internal _LIMIT_ORDER_RFQ_TYPEHASH = keccak256(
                        "OrderRFQ("
                            "uint256 info,"
                            "address makerAsset,"
                            "address takerAsset,"
                            "address maker,"
                            "address allowedSender,"
                            "uint256 makingAmount,"
                            "uint256 takingAmount"
                        ")"
                    );
                
                    function hash(OrderRFQ memory order, bytes32 domainSeparator) internal pure returns(bytes32 result) {
                        bytes32 typehash = _LIMIT_ORDER_RFQ_TYPEHASH;
                        bytes32 orderHash;
                        // this assembly is memory unsafe :(
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := sub(order, 0x20)
                
                            // keccak256(abi.encode(_LIMIT_ORDER_RFQ_TYPEHASH, order));
                            let tmp := mload(ptr)
                            mstore(ptr, typehash)
                            orderHash := keccak256(ptr, 0x100)
                            mstore(ptr, tmp)
                        }
                        return ECDSA.toTypedDataHash(domainSeparator, orderHash);
                    }
                }
                
                
                // File @openzeppelin/contracts/utils/[email protected]
                
                // OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)
                
                pragma solidity ^0.8.0;
                
                /**
                 * @dev String operations.
                 */
                library Strings {
                    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
                    uint8 private constant _ADDRESS_LENGTH = 20;
                
                    /**
                     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
                     */
                    function toString(uint256 value) internal pure returns (string memory) {
                        // Inspired by OraclizeAPI's implementation - MIT licence
                        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
                
                        if (value == 0) {
                            return "0";
                        }
                        uint256 temp = value;
                        uint256 digits;
                        while (temp != 0) {
                            digits++;
                            temp /= 10;
                        }
                        bytes memory buffer = new bytes(digits);
                        while (value != 0) {
                            digits -= 1;
                            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                            value /= 10;
                        }
                        return string(buffer);
                    }
                
                    /**
                     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
                     */
                    function toHexString(uint256 value) internal pure returns (string memory) {
                        if (value == 0) {
                            return "0x00";
                        }
                        uint256 temp = value;
                        uint256 length = 0;
                        while (temp != 0) {
                            length++;
                            temp >>= 8;
                        }
                        return toHexString(value, length);
                    }
                
                    /**
                     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
                     */
                    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] = _HEX_SYMBOLS[value & 0xf];
                            value >>= 4;
                        }
                        require(value == 0, "Strings: hex length insufficient");
                        return string(buffer);
                    }
                
                    /**
                     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
                     */
                    function toHexString(address addr) internal pure returns (string memory) {
                        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
                    }
                }
                
                
                // File @openzeppelin/contracts/utils/cryptography/[email protected]
                
                // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
                
                pragma solidity ^0.8.0;
                
                /**
                 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
                 *
                 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
                 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
                 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
                 *
                 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
                 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
                 * ({_hashTypedDataV4}).
                 *
                 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
                 * the chain id to protect against replay attacks on an eventual fork of the chain.
                 *
                 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
                 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
                 *
                 * _Available since v3.4._
                 */
                abstract contract EIP712 {
                    /* solhint-disable var-name-mixedcase */
                    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
                    // invalidate the cached domain separator if the chain id changes.
                    bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
                    uint256 private immutable _CACHED_CHAIN_ID;
                    address private immutable _CACHED_THIS;
                
                    bytes32 private immutable _HASHED_NAME;
                    bytes32 private immutable _HASHED_VERSION;
                    bytes32 private immutable _TYPE_HASH;
                
                    /* solhint-enable var-name-mixedcase */
                
                    /**
                     * @dev Initializes the domain separator and parameter caches.
                     *
                     * The meaning of `name` and `version` is specified in
                     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
                     *
                     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
                     * - `version`: the current major version of the signing domain.
                     *
                     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
                     * contract upgrade].
                     */
                    constructor(string memory name, string memory version) {
                        bytes32 hashedName = keccak256(bytes(name));
                        bytes32 hashedVersion = keccak256(bytes(version));
                        bytes32 typeHash = keccak256(
                            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
                        );
                        _HASHED_NAME = hashedName;
                        _HASHED_VERSION = hashedVersion;
                        _CACHED_CHAIN_ID = block.chainid;
                        _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
                        _CACHED_THIS = address(this);
                        _TYPE_HASH = typeHash;
                    }
                
                    /**
                     * @dev Returns the domain separator for the current chain.
                     */
                    function _domainSeparatorV4() internal view returns (bytes32) {
                        if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
                            return _CACHED_DOMAIN_SEPARATOR;
                        } else {
                            return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
                        }
                    }
                
                    function _buildDomainSeparator(
                        bytes32 typeHash,
                        bytes32 nameHash,
                        bytes32 versionHash
                    ) private view returns (bytes32) {
                        return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
                    }
                
                    /**
                     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
                     * function returns the hash of the fully encoded EIP712 message for this domain.
                     *
                     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
                     *
                     * ```solidity
                     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
                     *     keccak256("Mail(address to,string contents)"),
                     *     mailTo,
                     *     keccak256(bytes(mailContents))
                     * )));
                     * address signer = ECDSA.recover(digest, signature);
                     * ```
                     */
                    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
                        return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
                    }
                }
                
                
                // File @1inch/limit-order-protocol/contracts/libraries/[email protected]
                
                
                pragma solidity 0.8.17;
                
                library Errors {
                    error InvalidMsgValue();
                    error ETHTransferFailed();
                }
                
                
                // File @1inch/limit-order-protocol/contracts/helpers/[email protected]
                
                
                pragma solidity 0.8.17;
                
                /// @title A helper contract for calculations related to order amounts
                library AmountCalculator {
                    /// @notice Calculates maker amount
                    /// @return Result Floored maker amount
                    function getMakingAmount(uint256 orderMakerAmount, uint256 orderTakerAmount, uint256 swapTakerAmount) internal pure returns(uint256) {
                        return swapTakerAmount * orderMakerAmount / orderTakerAmount;
                    }
                
                    /// @notice Calculates taker amount
                    /// @return Result Ceiled taker amount
                    function getTakingAmount(uint256 orderMakerAmount, uint256 orderTakerAmount, uint256 swapMakerAmount) internal pure returns(uint256) {
                        return (swapMakerAmount * orderTakerAmount + orderMakerAmount - 1) / orderMakerAmount;
                    }
                }
                
                
                // File @1inch/limit-order-protocol/contracts/[email protected]
                
                
                pragma solidity 0.8.17;
                
                
                
                
                
                
                
                /// @title RFQ Limit Order mixin
                abstract contract OrderRFQMixin is EIP712, OnlyWethReceiver {
                    using SafeERC20 for IERC20;
                    using OrderRFQLib for OrderRFQLib.OrderRFQ;
                
                    error RFQZeroTargetIsForbidden();
                    error RFQPrivateOrder();
                    error RFQBadSignature();
                    error OrderExpired();
                    error MakingAmountExceeded();
                    error TakingAmountExceeded();
                    error RFQSwapWithZeroAmount();
                    error InvalidatedOrder();
                
                    /**
                     * @notice Emitted when RFQ gets filled
                     * @param orderHash Hash of the order
                     * @param makingAmount Amount of the maker asset that was transferred from maker to taker
                     */
                    event OrderFilledRFQ(
                        bytes32 orderHash,
                        uint256 makingAmount
                    );
                
                    uint256 private constant _RAW_CALL_GAS_LIMIT = 5000;
                    uint256 private constant _MAKER_AMOUNT_FLAG = 1 << 255;
                    uint256 private constant _SIGNER_SMART_CONTRACT_HINT = 1 << 254;
                    uint256 private constant _IS_VALID_SIGNATURE_65_BYTES = 1 << 253;
                    uint256 private constant _UNWRAP_WETH_FLAG = 1 << 252;
                    uint256 private constant _AMOUNT_MASK = ~(
                        _MAKER_AMOUNT_FLAG |
                        _SIGNER_SMART_CONTRACT_HINT |
                        _IS_VALID_SIGNATURE_65_BYTES |
                        _UNWRAP_WETH_FLAG
                    );
                
                    IWETH private immutable _WETH;  // solhint-disable-line var-name-mixedcase
                    mapping(address => mapping(uint256 => uint256)) private _invalidator;
                
                    constructor(IWETH weth) OnlyWethReceiver(address(weth)) {
                        _WETH = weth;
                    }
                
                    /**
                     * @notice Returns bitmask for double-spend invalidators based on lowest byte of order.info and filled quotes
                     * @param maker Maker address
                     * @param slot Slot number to return bitmask for
                     * @return result Each bit represents whether corresponding was already invalidated
                     */
                    function invalidatorForOrderRFQ(address maker, uint256 slot) external view returns(uint256 /* result */) {
                        return _invalidator[maker][slot];
                    }
                
                    /**
                     * @notice Cancels order's quote
                     * @param orderInfo Order info (only order id in lowest 64 bits is used)
                     */
                    function cancelOrderRFQ(uint256 orderInfo) external {
                        _invalidateOrder(msg.sender, orderInfo, 0);
                    }
                
                    /// @notice Cancels multiple order's quotes
                    function cancelOrderRFQ(uint256 orderInfo, uint256 additionalMask) external {
                        _invalidateOrder(msg.sender, orderInfo, additionalMask);
                    }
                
                    /**
                     * @notice Fills order's quote, fully or partially (whichever is possible)
                     * @param order Order quote to fill
                     * @param signature Signature to confirm quote ownership
                     * @param flagsAndAmount Fill configuration flags with amount packed in one slot
                     * @return filledMakingAmount Actual amount transferred from maker to taker
                     * @return filledTakingAmount Actual amount transferred from taker to maker
                     * @return orderHash Hash of the filled order
                     */
                    function fillOrderRFQ(
                        OrderRFQLib.OrderRFQ memory order,
                        bytes calldata signature,
                        uint256 flagsAndAmount
                    ) external payable returns(uint256 /* filledMakingAmount */, uint256 /* filledTakingAmount */, bytes32 /* orderHash */) {
                        return fillOrderRFQTo(order, signature, flagsAndAmount, msg.sender);
                    }
                
                    /**
                     * @notice Fills order's quote, fully or partially, with compact signature
                     * @param order Order quote to fill
                     * @param r R component of signature
                     * @param vs VS component of signature
                     * @param flagsAndAmount Fill configuration flags with amount packed in one slot
                     * - Bits 0-252 contain the amount to fill
                     * - Bit 253 is used to indicate whether signature is 64-bit (0) or 65-bit (1)
                     * - Bit 254 is used to indicate whether smart contract (1) signed the order or not (0)
                     * - Bit 255 is used to indicate whether maker (1) or taker amount (0) is given in the amount parameter
                     * @return filledMakingAmount Actual amount transferred from maker to taker
                     * @return filledTakingAmount Actual amount transferred from taker to maker
                     * @return orderHash Hash of the filled order
                     */
                    function fillOrderRFQCompact(
                        OrderRFQLib.OrderRFQ memory order,
                        bytes32 r,
                        bytes32 vs,
                        uint256 flagsAndAmount
                    ) external payable returns(uint256 filledMakingAmount, uint256 filledTakingAmount, bytes32 orderHash) {
                        orderHash = order.hash(_domainSeparatorV4());
                        if (flagsAndAmount & _SIGNER_SMART_CONTRACT_HINT != 0) {
                            if (flagsAndAmount & _IS_VALID_SIGNATURE_65_BYTES != 0) {
                                if (!ECDSA.isValidSignature65(order.maker, orderHash, r, vs)) revert RFQBadSignature();
                            } else {
                                if (!ECDSA.isValidSignature(order.maker, orderHash, r, vs)) revert RFQBadSignature();
                            }
                        } else {
                            if(!ECDSA.recoverOrIsValidSignature(order.maker, orderHash, r, vs)) revert RFQBadSignature();
                        }
                
                        (filledMakingAmount, filledTakingAmount) = _fillOrderRFQTo(order, flagsAndAmount, msg.sender);
                        emit OrderFilledRFQ(orderHash, filledMakingAmount);
                    }
                
                    /**
                     * @notice Same as `fillOrderRFQTo` but calls permit first.
                     * It allows to approve token spending and make a swap in one transaction.
                     * Also allows to specify funds destination instead of `msg.sender`
                     * @param order Order quote to fill
                     * @param signature Signature to confirm quote ownership
                     * @param flagsAndAmount Fill configuration flags with amount packed in one slot
                     * @param target Address that will receive swap funds
                     * @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call.
                     * @return filledMakingAmount Actual amount transferred from maker to taker
                     * @return filledTakingAmount Actual amount transferred from taker to maker
                     * @return orderHash Hash of the filled order
                     * @dev See tests for examples
                     */
                    function fillOrderRFQToWithPermit(
                        OrderRFQLib.OrderRFQ memory order,
                        bytes calldata signature,
                        uint256 flagsAndAmount,
                        address target,
                        bytes calldata permit
                    ) external returns(uint256 /* filledMakingAmount */, uint256 /* filledTakingAmount */, bytes32 /* orderHash */) {
                        IERC20(order.takerAsset).safePermit(permit);
                        return fillOrderRFQTo(order, signature, flagsAndAmount, target);
                    }
                
                    /**
                     * @notice Same as `fillOrderRFQ` but allows to specify funds destination instead of `msg.sender`
                     * @param order Order quote to fill
                     * @param signature Signature to confirm quote ownership
                     * @param flagsAndAmount Fill configuration flags with amount packed in one slot
                     * @param target Address that will receive swap funds
                     * @return filledMakingAmount Actual amount transferred from maker to taker
                     * @return filledTakingAmount Actual amount transferred from taker to maker
                     * @return orderHash Hash of the filled order
                     */
                    function fillOrderRFQTo(
                        OrderRFQLib.OrderRFQ memory order,
                        bytes calldata signature,
                        uint256 flagsAndAmount,
                        address target
                    ) public payable returns(uint256 filledMakingAmount, uint256 filledTakingAmount, bytes32 orderHash) {
                        orderHash = order.hash(_domainSeparatorV4());
                        if (flagsAndAmount & _SIGNER_SMART_CONTRACT_HINT != 0) {
                            if (flagsAndAmount & _IS_VALID_SIGNATURE_65_BYTES != 0 && signature.length != 65) revert RFQBadSignature();
                            if (!ECDSA.isValidSignature(order.maker, orderHash, signature)) revert RFQBadSignature();
                        } else {
                            if(!ECDSA.recoverOrIsValidSignature(order.maker, orderHash, signature)) revert RFQBadSignature();
                        }
                        (filledMakingAmount, filledTakingAmount) = _fillOrderRFQTo(order, flagsAndAmount, target);
                        emit OrderFilledRFQ(orderHash, filledMakingAmount);
                    }
                
                    function _fillOrderRFQTo(
                        OrderRFQLib.OrderRFQ memory order,
                        uint256 flagsAndAmount,
                        address target
                    ) private returns(uint256 makingAmount, uint256 takingAmount) {
                        if (target == address(0)) revert RFQZeroTargetIsForbidden();
                
                        address maker = order.maker;
                
                        // Validate order
                        if (order.allowedSender != address(0) && order.allowedSender != msg.sender) revert RFQPrivateOrder();
                
                        {  // Stack too deep
                            uint256 info = order.info;
                            // Check time expiration
                            uint256 expiration = uint128(info) >> 64;
                            if (expiration != 0 && block.timestamp > expiration) revert OrderExpired(); // solhint-disable-line not-rely-on-time
                            _invalidateOrder(maker, info, 0);
                        }
                
                        {  // Stack too deep
                            uint256 orderMakingAmount = order.makingAmount;
                            uint256 orderTakingAmount = order.takingAmount;
                            uint256 amount = flagsAndAmount & _AMOUNT_MASK;
                            // Compute partial fill if needed
                            if (amount == 0) {
                                // zero amount means whole order
                                makingAmount = orderMakingAmount;
                                takingAmount = orderTakingAmount;
                            }
                            else if (flagsAndAmount & _MAKER_AMOUNT_FLAG != 0) {
                                if (amount > orderMakingAmount) revert MakingAmountExceeded();
                                makingAmount = amount;
                                takingAmount = AmountCalculator.getTakingAmount(orderMakingAmount, orderTakingAmount, makingAmount);
                            }
                            else {
                                if (amount > orderTakingAmount) revert TakingAmountExceeded();
                                takingAmount = amount;
                                makingAmount = AmountCalculator.getMakingAmount(orderMakingAmount, orderTakingAmount, takingAmount);
                            }
                        }
                
                        if (makingAmount == 0 || takingAmount == 0) revert RFQSwapWithZeroAmount();
                
                        // Maker => Taker
                        if (order.makerAsset == address(_WETH) && flagsAndAmount & _UNWRAP_WETH_FLAG != 0) {
                            _WETH.transferFrom(maker, address(this), makingAmount);
                            _WETH.withdraw(makingAmount);
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, ) = target.call{value: makingAmount, gas: _RAW_CALL_GAS_LIMIT}("");
                            if (!success) revert Errors.ETHTransferFailed();
                        } else {
                            IERC20(order.makerAsset).safeTransferFrom(maker, target, makingAmount);
                        }
                
                        // Taker => Maker
                        if (order.takerAsset == address(_WETH) && msg.value > 0) {
                            if (msg.value != takingAmount) revert Errors.InvalidMsgValue();
                            _WETH.deposit{ value: takingAmount }();
                            _WETH.transfer(maker, takingAmount);
                        } else {
                            if (msg.value != 0) revert Errors.InvalidMsgValue();
                            IERC20(order.takerAsset).safeTransferFrom(msg.sender, maker, takingAmount);
                        }
                    }
                
                    function _invalidateOrder(address maker, uint256 orderInfo, uint256 additionalMask) private {
                        uint256 invalidatorSlot = uint64(orderInfo) >> 8;
                        uint256 invalidatorBits = (1 << uint8(orderInfo)) | additionalMask;
                        mapping(uint256 => uint256) storage invalidatorStorage = _invalidator[maker];
                        uint256 invalidator = invalidatorStorage[invalidatorSlot];
                        if (invalidator & invalidatorBits == invalidatorBits) revert InvalidatedOrder();
                        invalidatorStorage[invalidatorSlot] = invalidator | invalidatorBits;
                    }
                }
                
                
                // File @1inch/limit-order-protocol/contracts/[email protected]
                
                
                pragma solidity 0.8.17;
                
                library OrderLib {
                    struct Order {
                        uint256 salt;
                        address makerAsset;
                        address takerAsset;
                        address maker;
                        address receiver;
                        address allowedSender;  // equals to Zero address on public orders
                        uint256 makingAmount;
                        uint256 takingAmount;
                        uint256 offsets;
                        // bytes makerAssetData;
                        // bytes takerAssetData;
                        // bytes getMakingAmount; // this.staticcall(abi.encodePacked(bytes, swapTakerAmount)) => (swapMakerAmount)
                        // bytes getTakingAmount; // this.staticcall(abi.encodePacked(bytes, swapMakerAmount)) => (swapTakerAmount)
                        // bytes predicate;       // this.staticcall(bytes) => (bool)
                        // bytes permit;          // On first fill: permit.1.call(abi.encodePacked(permit.selector, permit.2))
                        // bytes preInteraction;
                        // bytes postInteraction;
                        bytes interactions; // concat(makerAssetData, takerAssetData, getMakingAmount, getTakingAmount, predicate, permit, preIntercation, postInteraction)
                    }
                
                    bytes32 constant internal _LIMIT_ORDER_TYPEHASH = keccak256(
                        "Order("
                            "uint256 salt,"
                            "address makerAsset,"
                            "address takerAsset,"
                            "address maker,"
                            "address receiver,"
                            "address allowedSender,"
                            "uint256 makingAmount,"
                            "uint256 takingAmount,"
                            "uint256 offsets,"
                            "bytes interactions"
                        ")"
                    );
                
                    enum DynamicField {
                        MakerAssetData,
                        TakerAssetData,
                        GetMakingAmount,
                        GetTakingAmount,
                        Predicate,
                        Permit,
                        PreInteraction,
                        PostInteraction
                    }
                
                    function getterIsFrozen(bytes calldata getter) internal pure returns(bool) {
                        return getter.length == 1 && getter[0] == "x";
                    }
                
                    function _get(Order calldata order, DynamicField field) private pure returns(bytes calldata) {
                        uint256 bitShift = uint256(field) << 5; // field * 32
                        return order.interactions[
                            uint32((order.offsets << 32) >> bitShift):
                            uint32(order.offsets >> bitShift)
                        ];
                    }
                
                    function makerAssetData(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.MakerAssetData);
                    }
                
                    function takerAssetData(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.TakerAssetData);
                    }
                
                    function getMakingAmount(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.GetMakingAmount);
                    }
                
                    function getTakingAmount(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.GetTakingAmount);
                    }
                
                    function predicate(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.Predicate);
                    }
                
                    function permit(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.Permit);
                    }
                
                    function preInteraction(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.PreInteraction);
                    }
                
                    function postInteraction(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.PostInteraction);
                    }
                
                    function hash(Order calldata order, bytes32 domainSeparator) internal pure returns(bytes32 result) {
                        bytes calldata interactions = order.interactions;
                        bytes32 typehash = _LIMIT_ORDER_TYPEHASH;
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                
                            // keccak256(abi.encode(_LIMIT_ORDER_TYPEHASH, orderWithoutInteractions, keccak256(order.interactions)));
                            calldatacopy(ptr, interactions.offset, interactions.length)
                            mstore(add(ptr, 0x140), keccak256(ptr, interactions.length))
                            calldatacopy(add(ptr, 0x20), order, 0x120)
                            mstore(ptr, typehash)
                            result := keccak256(ptr, 0x160)
                        }
                        result = ECDSA.toTypedDataHash(domainSeparator, result);
                    }
                }
                
                
                // File @1inch/limit-order-protocol/contracts/libraries/[email protected]
                
                
                pragma solidity 0.8.17;
                
                /// @title Library with gas efficient alternatives to `abi.decode`
                library ArgumentsDecoder {
                    error IncorrectDataLength();
                
                    function decodeUint256(bytes calldata data, uint256 offset) internal pure returns(uint256 value) {
                        unchecked { if (data.length < offset + 32) revert IncorrectDataLength(); }
                        // no memory ops inside so this insertion is automatically memory safe
                        assembly { // solhint-disable-line no-inline-assembly
                            value := calldataload(add(data.offset, offset))
                        }
                    }
                
                    function decodeSelector(bytes calldata data) internal pure returns(bytes4 value) {
                        if (data.length < 4) revert IncorrectDataLength();
                        // no memory ops inside so this insertion is automatically memory safe
                        assembly { // solhint-disable-line no-inline-assembly
                            value := calldataload(data.offset)
                        }
                    }
                
                    function decodeTailCalldata(bytes calldata data, uint256 tailOffset) internal pure returns(bytes calldata args) {
                        if (data.length < tailOffset) revert IncorrectDataLength();
                        // no memory ops inside so this insertion is automatically memory safe
                        assembly {  // solhint-disable-line no-inline-assembly
                            args.offset := add(data.offset, tailOffset)
                            args.length := sub(data.length, tailOffset)
                        }
                    }
                
                    function decodeTargetAndCalldata(bytes calldata data) internal pure returns(address target, bytes calldata args) {
                        if (data.length < 20) revert IncorrectDataLength();
                        // no memory ops inside so this insertion is automatically memory safe
                        assembly {  // solhint-disable-line no-inline-assembly
                            target := shr(96, calldataload(data.offset))
                            args.offset := add(data.offset, 20)
                            args.length := sub(data.length, 20)
                        }
                    }
                }
                
                
                // File @1inch/limit-order-protocol/contracts/helpers/[email protected]
                
                
                pragma solidity 0.8.17;
                
                /// @title A helper contract for managing nonce of tx sender
                contract NonceManager {
                    error AdvanceNonceFailed();
                    event NonceIncreased(address indexed maker, uint256 newNonce);
                
                    mapping(address => uint256) public nonce;
                
                    /// @notice Advances nonce by one
                    function increaseNonce() external {
                        advanceNonce(1);
                    }
                
                    /// @notice Advances nonce by specified amount
                    function advanceNonce(uint8 amount) public {
                        if (amount == 0) revert AdvanceNonceFailed();
                        uint256 newNonce = nonce[msg.sender] + amount;
                        nonce[msg.sender] = newNonce;
                        emit NonceIncreased(msg.sender, newNonce);
                    }
                
                    /// @notice Checks if `makerAddress` has specified `makerNonce`
                    /// @return Result True if `makerAddress` has specified nonce. Otherwise, false
                    function nonceEquals(address makerAddress, uint256 makerNonce) public view returns(bool) {
                        return nonce[makerAddress] == makerNonce;
                    }
                }
                
                
                // File @1inch/limit-order-protocol/contracts/helpers/[email protected]
                
                
                pragma solidity 0.8.17;
                
                
                /// @title A helper contract for executing boolean functions on arbitrary target call results
                contract PredicateHelper is NonceManager {
                    using ArgumentsDecoder for bytes;
                
                    error ArbitraryStaticCallFailed();
                
                    /// @notice Calls every target with corresponding data
                    /// @return Result True if call to any target returned True. Otherwise, false
                    function or(uint256 offsets, bytes calldata data) public view returns(bool) {
                        uint256 current;
                        uint256 previous;
                        for (uint256 i = 0; (current = uint32(offsets >> i)) != 0; i += 32) {
                            (bool success, uint256 res) = _selfStaticCall(data[previous:current]);
                            if (success && res == 1) {
                                return true;
                            }
                            previous = current;
                        }
                        return false;
                    }
                
                    /// @notice Calls every target with corresponding data
                    /// @return Result True if calls to all targets returned True. Otherwise, false
                    function and(uint256 offsets, bytes calldata data) public view returns(bool) {
                        uint256 current;
                        uint256 previous;
                        for (uint256 i = 0; (current = uint32(offsets >> i)) != 0; i += 32) {
                            (bool success, uint256 res) = _selfStaticCall(data[previous:current]);
                            if (!success || res != 1) {
                                return false;
                            }
                            previous = current;
                        }
                        return true;
                    }
                
                    /// @notice Calls target with specified data and tests if it's equal to the value
                    /// @param value Value to test
                    /// @return Result True if call to target returns the same value as `value`. Otherwise, false
                    function eq(uint256 value, bytes calldata data) public view returns(bool) {
                        (bool success, uint256 res) = _selfStaticCall(data);
                        return success && res == value;
                    }
                
                    /// @notice Calls target with specified data and tests if it's lower than value
                    /// @param value Value to test
                    /// @return Result True if call to target returns value which is lower than `value`. Otherwise, false
                    function lt(uint256 value, bytes calldata data) public view returns(bool) {
                        (bool success, uint256 res) = _selfStaticCall(data);
                        return success && res < value;
                    }
                
                    /// @notice Calls target with specified data and tests if it's bigger than value
                    /// @param value Value to test
                    /// @return Result True if call to target returns value which is bigger than `value`. Otherwise, false
                    function gt(uint256 value, bytes calldata data) public view returns(bool) {
                        (bool success, uint256 res) = _selfStaticCall(data);
                        return success && res > value;
                    }
                
                    /// @notice Checks passed time against block timestamp
                    /// @return Result True if current block timestamp is lower than `time`. Otherwise, false
                    function timestampBelow(uint256 time) public view returns(bool) {
                        return block.timestamp < time;  // solhint-disable-line not-rely-on-time
                    }
                
                    /// @notice Performs an arbitrary call to target with data
                    /// @return Result Bytes transmuted to uint256
                    function arbitraryStaticCall(address target, bytes calldata data) public view returns(uint256) {
                        (bool success, uint256 res) = _staticcallForUint(target, data);
                        if (!success) revert ArbitraryStaticCallFailed();
                        return res;
                    }
                
                    function timestampBelowAndNonceEquals(uint256 timeNonceAccount) public view returns(bool) {
                        uint256 _time = uint48(timeNonceAccount >> 208);
                        uint256 _nonce = uint48(timeNonceAccount >> 160);
                        address _account = address(uint160(timeNonceAccount));
                        return timestampBelow(_time) && nonceEquals(_account, _nonce);
                    }
                
                    function _selfStaticCall(bytes calldata data) internal view returns(bool, uint256) {
                        uint256 selector = uint32(data.decodeSelector());
                        uint256 arg = data.decodeUint256(4);
                
                        // special case for the most often used predicate
                        if (selector == uint32(this.timestampBelowAndNonceEquals.selector)) {  // 0x2cc2878d
                            return (true, timestampBelowAndNonceEquals(arg) ? 1 : 0);
                        }
                
                        if (selector < uint32(this.arbitraryStaticCall.selector)) {  // 0xbf15fcd8
                            if (selector < uint32(this.eq.selector)) {  // 0x6fe7b0ba
                                if (selector == uint32(this.gt.selector)) {  // 0x4f38e2b8
                                    return (true, gt(arg, data.decodeTailCalldata(100)) ? 1 : 0);
                                } else if (selector == uint32(this.timestampBelow.selector)) {  // 0x63592c2b
                                    return (true, timestampBelow(arg) ? 1 : 0);
                                }
                            } else {
                                if (selector == uint32(this.eq.selector)) {  // 0x6fe7b0ba
                                    return (true, eq(arg, data.decodeTailCalldata(100)) ? 1 : 0);
                                } else if (selector == uint32(this.or.selector)) {  // 0x74261145
                                    return (true, or(arg, data.decodeTailCalldata(100)) ? 1 : 0);
                                }
                            }
                        } else {
                            if (selector < uint32(this.lt.selector)) {  // 0xca4ece22
                                if (selector == uint32(this.arbitraryStaticCall.selector)) {  // 0xbf15fcd8
                                    return (true, arbitraryStaticCall(address(uint160(arg)), data.decodeTailCalldata(100)));
                                } else if (selector == uint32(this.and.selector)) {  // 0xbfa75143
                                    return (true, and(arg, data.decodeTailCalldata(100)) ? 1 : 0);
                                }
                            } else {
                                if (selector == uint32(this.lt.selector)) {  // 0xca4ece22
                                    return (true, lt(arg, data.decodeTailCalldata(100)) ? 1 : 0);
                                } else if (selector == uint32(this.nonceEquals.selector)) {  // 0xcf6fc6e3
                                    return (true, nonceEquals(address(uint160(arg)), data.decodeUint256(0x24)) ? 1 : 0);
                                }
                            }
                        }
                
                        return _staticcallForUint(address(this), data);
                    }
                
                    function _staticcallForUint(address target, bytes calldata input) private view returns(bool success, uint256 res) {
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let data := mload(0x40)
                
                            calldatacopy(data, input.offset, input.length)
                            success := staticcall(gas(), target, data, input.length, 0x0, 0x20)
                            success := and(success, eq(returndatasize(), 32))
                            if success {
                                res := mload(0)
                            }
                        }
                    }
                }
                
                
                // File @1inch/limit-order-protocol/contracts/interfaces/[email protected]
                
                
                pragma solidity 0.8.17;
                
                interface IOrderMixin {
                    /**
                     * @notice Returns unfilled amount for order. Throws if order does not exist
                     * @param orderHash Order's hash. Can be obtained by the `hashOrder` function
                     * @return amount Unfilled amount
                     */
                    function remaining(bytes32 orderHash) external view returns(uint256 amount);
                
                    /**
                     * @notice Returns unfilled amount for order
                     * @param orderHash Order's hash. Can be obtained by the `hashOrder` function
                     * @return rawAmount Unfilled amount of order plus one if order exists. Otherwise 0
                     */
                    function remainingRaw(bytes32 orderHash) external view returns(uint256 rawAmount);
                
                    /**
                     * @notice Same as `remainingRaw` but for multiple orders
                     * @param orderHashes Array of hashes
                     * @return rawAmounts Array of amounts for each order plus one if order exists or 0 otherwise
                     */
                    function remainingsRaw(bytes32[] memory orderHashes) external view returns(uint256[] memory rawAmounts);
                
                    /**
                     * @notice Checks order predicate
                     * @param order Order to check predicate for
                     * @return result Predicate evaluation result. True if predicate allows to fill the order, false otherwise
                     */
                    function checkPredicate(OrderLib.Order calldata order) external view returns(bool result);
                
                    /**
                     * @notice Returns order hash according to EIP712 standard
                     * @param order Order to get hash for
                     * @return orderHash Hash of the order
                     */
                    function hashOrder(OrderLib.Order calldata order) external view returns(bytes32);
                
                    /**
                     * @notice Delegates execution to custom implementation. Could be used to validate if `transferFrom` works properly
                     * @dev The function always reverts and returns the simulation results in revert data.
                     * @param target Addresses that will be delegated
                     * @param data Data that will be passed to delegatee
                     */
                    function simulate(address target, bytes calldata data) external;
                
                    /**
                     * @notice Cancels order.
                     * @dev Order is cancelled by setting remaining amount to _ORDER_FILLED value
                     * @param order Order quote to cancel
                     * @return orderRemaining Unfilled amount of order before cancellation
                     * @return orderHash Hash of the filled order
                     */
                    function cancelOrder(OrderLib.Order calldata order) external returns(uint256 orderRemaining, bytes32 orderHash);
                
                    /**
                     * @notice Fills an order. If one doesn't exist (first fill) it will be created using order.makerAssetData
                     * @param order Order quote to fill
                     * @param signature Signature to confirm quote ownership
                     * @param interaction A call data for InteractiveNotificationReceiver. Taker may execute interaction after getting maker assets and before sending taker assets.
                     * @param makingAmount Making amount
                     * @param takingAmount Taking amount
                     * @param skipPermitAndThresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount. Top-most bit specifies whether taker wants to skip maker's permit.
                     * @return actualMakingAmount Actual amount transferred from maker to taker
                     * @return actualTakingAmount Actual amount transferred from taker to maker
                     * @return orderHash Hash of the filled order
                     */
                    function fillOrder(
                        OrderLib.Order calldata order,
                        bytes calldata signature,
                        bytes calldata interaction,
                        uint256 makingAmount,
                        uint256 takingAmount,
                        uint256 skipPermitAndThresholdAmount
                    ) external payable returns(uint256 actualMakingAmount, uint256 actualTakingAmount, bytes32 orderHash);
                
                    /**
                     * @notice Same as `fillOrderTo` but calls permit first,
                     * allowing to approve token spending and make a swap in one transaction.
                     * Also allows to specify funds destination instead of `msg.sender`
                     * @dev See tests for examples
                     * @param order Order quote to fill
                     * @param signature Signature to confirm quote ownership
                     * @param interaction A call data for InteractiveNotificationReceiver. Taker may execute interaction after getting maker assets and before sending taker assets.
                     * @param makingAmount Making amount
                     * @param takingAmount Taking amount
                     * @param skipPermitAndThresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount. Top-most bit specifies whether taker wants to skip maker's permit.
                     * @param target Address that will receive swap funds
                     * @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call.
                     * @return actualMakingAmount Actual amount transferred from maker to taker
                     * @return actualTakingAmount Actual amount transferred from taker to maker
                     * @return orderHash Hash of the filled order
                     */
                    function fillOrderToWithPermit(
                        OrderLib.Order calldata order,
                        bytes calldata signature,
                        bytes calldata interaction,
                        uint256 makingAmount,
                        uint256 takingAmount,
                        uint256 skipPermitAndThresholdAmount,
                        address target,
                        bytes calldata permit
                    ) external returns(uint256 actualMakingAmount, uint256 actualTakingAmount, bytes32 orderHash);
                
                    /**
                     * @notice Same as `fillOrder` but allows to specify funds destination instead of `msg.sender`
                     * @param order_ Order quote to fill
                     * @param signature Signature to confirm quote ownership
                     * @param interaction A call data for InteractiveNotificationReceiver. Taker may execute interaction after getting maker assets and before sending taker assets.
                     * @param makingAmount Making amount
                     * @param takingAmount Taking amount
                     * @param skipPermitAndThresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount. Top-most bit specifies whether taker wants to skip maker's permit.
                     * @param target Address that will receive swap funds
                     * @return actualMakingAmount Actual amount transferred from maker to taker
                     * @return actualTakingAmount Actual amount transferred from taker to maker
                     * @return orderHash Hash of the filled order
                     */
                    function fillOrderTo(
                        OrderLib.Order calldata order_,
                        bytes calldata signature,
                        bytes calldata interaction,
                        uint256 makingAmount,
                        uint256 takingAmount,
                        uint256 skipPermitAndThresholdAmount,
                        address target
                    ) external payable returns(uint256 actualMakingAmount, uint256 actualTakingAmount, bytes32 orderHash);
                }
                
                
                // File @1inch/limit-order-protocol/contracts/interfaces/[email protected]
                
                
                pragma solidity 0.8.17;
                
                /// @title Interface for interactor which acts between `maker => taker` and `taker => maker` transfers.
                interface PreInteractionNotificationReceiver {
                    function fillOrderPreInteraction(
                        bytes32 orderHash,
                        address maker,
                        address taker,
                        uint256 makingAmount,
                        uint256 takingAmount,
                        uint256 remainingAmount,
                        bytes memory interactiveData
                    ) external;
                }
                
                interface PostInteractionNotificationReceiver {
                    /// @notice Callback method that gets called after taker transferred funds to maker but before
                    /// the opposite transfer happened
                    function fillOrderPostInteraction(
                        bytes32 orderHash,
                        address maker,
                        address taker,
                        uint256 makingAmount,
                        uint256 takingAmount,
                        uint256 remainingAmount,
                        bytes memory interactiveData
                    ) external;
                }
                
                interface InteractionNotificationReceiver {
                    function fillOrderInteraction(
                        address taker,
                        uint256 makingAmount,
                        uint256 takingAmount,
                        bytes memory interactiveData
                    ) external returns(uint256 offeredTakingAmount);
                }
                
                
                // File @1inch/limit-order-protocol/contracts/[email protected]
                
                
                pragma solidity 0.8.17;
                
                
                
                
                
                
                
                
                
                
                
                /// @title Regular Limit Order mixin
                abstract contract OrderMixin is IOrderMixin, EIP712, PredicateHelper {
                    using SafeERC20 for IERC20;
                    using ArgumentsDecoder for bytes;
                    using OrderLib for OrderLib.Order;
                
                    error UnknownOrder();
                    error AccessDenied();
                    error AlreadyFilled();
                    error PermitLengthTooLow();
                    error ZeroTargetIsForbidden();
                    error RemainingAmountIsZero();
                    error PrivateOrder();
                    error BadSignature();
                    error ReentrancyDetected();
                    error PredicateIsNotTrue();
                    error OnlyOneAmountShouldBeZero();
                    error TakingAmountTooHigh();
                    error MakingAmountTooLow();
                    error SwapWithZeroAmount();
                    error TransferFromMakerToTakerFailed();
                    error TransferFromTakerToMakerFailed();
                    error WrongAmount();
                    error WrongGetter();
                    error GetAmountCallFailed();
                    error TakingAmountIncreased();
                    error SimulationResults(bool success, bytes res);
                
                    /// @notice Emitted every time order gets filled, including partial fills
                    event OrderFilled(
                        address indexed maker,
                        bytes32 orderHash,
                        uint256 remaining
                    );
                
                    /// @notice Emitted when order gets cancelled
                    event OrderCanceled(
                        address indexed maker,
                        bytes32 orderHash,
                        uint256 remainingRaw
                    );
                
                    uint256 constant private _ORDER_DOES_NOT_EXIST = 0;
                    uint256 constant private _ORDER_FILLED = 1;
                    uint256 constant private _SKIP_PERMIT_FLAG = 1 << 255;
                    uint256 constant private _THRESHOLD_MASK = ~_SKIP_PERMIT_FLAG;
                
                    IWETH private immutable _WETH;  // solhint-disable-line var-name-mixedcase
                    /// @notice Stores unfilled amounts for each order plus one.
                    /// Therefore 0 means order doesn't exist and 1 means order was filled
                    mapping(bytes32 => uint256) private _remaining;
                
                    constructor(IWETH weth) {
                        _WETH = weth;
                    }
                
                    /**
                     * @notice See {IOrderMixin-remaining}.
                     */
                    function remaining(bytes32 orderHash) external view returns(uint256 /* amount */) {
                        uint256 amount = _remaining[orderHash];
                        if (amount == _ORDER_DOES_NOT_EXIST) revert UnknownOrder();
                        unchecked { return amount - 1; }
                    }
                
                    /**
                     * @notice See {IOrderMixin-remainingRaw}.
                     */
                    function remainingRaw(bytes32 orderHash) external view returns(uint256 /* rawAmount */) {
                        return _remaining[orderHash];
                    }
                
                    /**
                     * @notice See {IOrderMixin-remainingsRaw}.
                     */
                    function remainingsRaw(bytes32[] memory orderHashes) external view returns(uint256[] memory /* rawAmounts */) {
                        uint256[] memory results = new uint256[](orderHashes.length);
                        for (uint256 i = 0; i < orderHashes.length; i++) {
                            results[i] = _remaining[orderHashes[i]];
                        }
                        return results;
                    }
                
                    /**
                     * @notice See {IOrderMixin-simulate}.
                     */
                    function simulate(address target, bytes calldata data) external {
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, bytes memory result) = target.delegatecall(data);
                        revert SimulationResults(success, result);
                    }
                
                    /**
                     * @notice See {IOrderMixin-cancelOrder}.
                     */
                    function cancelOrder(OrderLib.Order calldata order) external returns(uint256 orderRemaining, bytes32 orderHash) {
                        if (order.maker != msg.sender) revert AccessDenied();
                
                        orderHash = hashOrder(order);
                        orderRemaining = _remaining[orderHash];
                        if (orderRemaining == _ORDER_FILLED) revert AlreadyFilled();
                        emit OrderCanceled(msg.sender, orderHash, orderRemaining);
                        _remaining[orderHash] = _ORDER_FILLED;
                    }
                
                    /**
                     * @notice See {IOrderMixin-fillOrder}.
                     */
                    function fillOrder(
                        OrderLib.Order calldata order,
                        bytes calldata signature,
                        bytes calldata interaction,
                        uint256 makingAmount,
                        uint256 takingAmount,
                        uint256 skipPermitAndThresholdAmount
                    ) external payable returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */, bytes32 /* orderHash */) {
                        return fillOrderTo(order, signature, interaction, makingAmount, takingAmount, skipPermitAndThresholdAmount, msg.sender);
                    }
                
                    /**
                     * @notice See {IOrderMixin-fillOrderToWithPermit}.
                     */
                    function fillOrderToWithPermit(
                        OrderLib.Order calldata order,
                        bytes calldata signature,
                        bytes calldata interaction,
                        uint256 makingAmount,
                        uint256 takingAmount,
                        uint256 skipPermitAndThresholdAmount,
                        address target,
                        bytes calldata permit
                    ) external returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */, bytes32 /* orderHash */) {
                        if (permit.length < 20) revert PermitLengthTooLow();
                        {  // Stack too deep
                            (address token, bytes calldata permitData) = permit.decodeTargetAndCalldata();
                            IERC20(token).safePermit(permitData);
                        }
                        return fillOrderTo(order, signature, interaction, makingAmount, takingAmount, skipPermitAndThresholdAmount, target);
                    }
                
                    /**
                     * @notice See {IOrderMixin-fillOrderTo}.
                     */
                    function fillOrderTo(
                        OrderLib.Order calldata order_,
                        bytes calldata signature,
                        bytes calldata interaction,
                        uint256 makingAmount,
                        uint256 takingAmount,
                        uint256 skipPermitAndThresholdAmount,
                        address target
                    ) public payable returns(uint256 actualMakingAmount, uint256 actualTakingAmount, bytes32 orderHash) {
                        if (target == address(0)) revert ZeroTargetIsForbidden();
                        orderHash = hashOrder(order_);
                
                        OrderLib.Order calldata order = order_; // Helps with "Stack too deep"
                        actualMakingAmount = makingAmount;
                        actualTakingAmount = takingAmount;
                
                        uint256 remainingMakingAmount = _remaining[orderHash];
                        if (remainingMakingAmount == _ORDER_FILLED) revert RemainingAmountIsZero();
                        if (order.allowedSender != address(0) && order.allowedSender != msg.sender) revert PrivateOrder();
                        if (remainingMakingAmount == _ORDER_DOES_NOT_EXIST) {
                            // First fill: validate order and permit maker asset
                            if (!ECDSA.recoverOrIsValidSignature(order.maker, orderHash, signature)) revert BadSignature();
                            remainingMakingAmount = order.makingAmount;
                
                            bytes calldata permit = order.permit();
                            if (skipPermitAndThresholdAmount & _SKIP_PERMIT_FLAG == 0 && permit.length >= 20) {
                                // proceed only if taker is willing to execute permit and its length is enough to store address
                                (address token, bytes calldata permitCalldata) = permit.decodeTargetAndCalldata();
                                IERC20(token).safePermit(permitCalldata);
                                if (_remaining[orderHash] != _ORDER_DOES_NOT_EXIST) revert ReentrancyDetected();
                            }
                        } else {
                            unchecked { remainingMakingAmount -= 1; }
                        }
                
                        // Check if order is valid
                        if (order.predicate().length > 0) {
                            if (!checkPredicate(order)) revert PredicateIsNotTrue();
                        }
                
                        // Compute maker and taker assets amount
                        if ((actualTakingAmount == 0) == (actualMakingAmount == 0)) {
                            revert OnlyOneAmountShouldBeZero();
                        } else if (actualTakingAmount == 0) {
                            if (actualMakingAmount > remainingMakingAmount) {
                                actualMakingAmount = remainingMakingAmount;
                            }
                            actualTakingAmount = _getTakingAmount(order.getTakingAmount(), order.makingAmount, actualMakingAmount, order.takingAmount, remainingMakingAmount, orderHash);
                            uint256 thresholdAmount = skipPermitAndThresholdAmount & _THRESHOLD_MASK;
                            // check that actual rate is not worse than what was expected
                            // actualTakingAmount / actualMakingAmount <= thresholdAmount / makingAmount
                            if (actualTakingAmount * makingAmount > thresholdAmount * actualMakingAmount) revert TakingAmountTooHigh();
                        } else {
                            actualMakingAmount = _getMakingAmount(order.getMakingAmount(), order.takingAmount, actualTakingAmount, order.makingAmount, remainingMakingAmount, orderHash);
                            if (actualMakingAmount > remainingMakingAmount) {
                                actualMakingAmount = remainingMakingAmount;
                                actualTakingAmount = _getTakingAmount(order.getTakingAmount(), order.makingAmount, actualMakingAmount, order.takingAmount, remainingMakingAmount, orderHash);
                                if (actualTakingAmount > takingAmount) revert TakingAmountIncreased();
                            }
                            uint256 thresholdAmount = skipPermitAndThresholdAmount & _THRESHOLD_MASK;
                            // check that actual rate is not worse than what was expected
                            // actualMakingAmount / actualTakingAmount >= thresholdAmount / takingAmount
                            if (actualMakingAmount * takingAmount < thresholdAmount * actualTakingAmount) revert MakingAmountTooLow();
                        }
                
                        if (actualMakingAmount == 0 || actualTakingAmount == 0) revert SwapWithZeroAmount();
                
                        // Update remaining amount in storage
                        unchecked {
                            remainingMakingAmount = remainingMakingAmount - actualMakingAmount;
                            _remaining[orderHash] = remainingMakingAmount + 1;
                        }
                        emit OrderFilled(order_.maker, orderHash, remainingMakingAmount);
                
                        // Maker can handle funds interactively
                        if (order.preInteraction().length >= 20) {
                            // proceed only if interaction length is enough to store address
                            (address interactionTarget, bytes calldata interactionData) = order.preInteraction().decodeTargetAndCalldata();
                            PreInteractionNotificationReceiver(interactionTarget).fillOrderPreInteraction(
                                orderHash, order.maker, msg.sender, actualMakingAmount, actualTakingAmount, remainingMakingAmount, interactionData
                            );
                        }
                
                        // Maker => Taker
                        if (!_callTransferFrom(
                            order.makerAsset,
                            order.maker,
                            target,
                            actualMakingAmount,
                            order.makerAssetData()
                        )) revert TransferFromMakerToTakerFailed();
                
                        if (interaction.length >= 20) {
                            // proceed only if interaction length is enough to store address
                            (address interactionTarget, bytes calldata interactionData) = interaction.decodeTargetAndCalldata();
                            uint256 offeredTakingAmount = InteractionNotificationReceiver(interactionTarget).fillOrderInteraction(
                                msg.sender, actualMakingAmount, actualTakingAmount, interactionData
                            );
                
                            if (offeredTakingAmount > actualTakingAmount &&
                                !OrderLib.getterIsFrozen(order.getMakingAmount()) &&
                                !OrderLib.getterIsFrozen(order.getTakingAmount()))
                            {
                                actualTakingAmount = offeredTakingAmount;
                            }
                        }
                
                        // Taker => Maker
                        if (order.takerAsset == address(_WETH) && msg.value > 0) {
                            if (msg.value < actualTakingAmount) revert Errors.InvalidMsgValue();
                            if (msg.value > actualTakingAmount) {
                                unchecked {
                                    (bool success, ) = msg.sender.call{value: msg.value - actualTakingAmount}("");  // solhint-disable-line avoid-low-level-calls
                                    if (!success) revert Errors.ETHTransferFailed();
                                }
                            }
                            _WETH.deposit{ value: actualTakingAmount }();
                            _WETH.transfer(order.receiver == address(0) ? order.maker : order.receiver, actualTakingAmount);
                        } else {
                            if (msg.value != 0) revert Errors.InvalidMsgValue();
                            if (!_callTransferFrom(
                                order.takerAsset,
                                msg.sender,
                                order.receiver == address(0) ? order.maker : order.receiver,
                                actualTakingAmount,
                                order.takerAssetData()
                            )) revert TransferFromTakerToMakerFailed();
                        }
                
                        // Maker can handle funds interactively
                        if (order.postInteraction().length >= 20) {
                            // proceed only if interaction length is enough to store address
                            (address interactionTarget, bytes calldata interactionData) = order.postInteraction().decodeTargetAndCalldata();
                            PostInteractionNotificationReceiver(interactionTarget).fillOrderPostInteraction(
                                 orderHash, order.maker, msg.sender, actualMakingAmount, actualTakingAmount, remainingMakingAmount, interactionData
                            );
                        }
                    }
                
                    /**
                     * @notice See {IOrderMixin-checkPredicate}.
                     */
                    function checkPredicate(OrderLib.Order calldata order) public view returns(bool) {
                        (bool success, uint256 res) = _selfStaticCall(order.predicate());
                        return success && res == 1;
                    }
                
                    /**
                     * @notice See {IOrderMixin-hashOrder}.
                     */
                    function hashOrder(OrderLib.Order calldata order) public view returns(bytes32) {
                        return order.hash(_domainSeparatorV4());
                    }
                
                    function _callTransferFrom(address asset, address from, address to, uint256 amount, bytes calldata input) private returns(bool success) {
                        bytes4 selector = IERC20.transferFrom.selector;
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let data := mload(0x40)
                
                            mstore(data, selector)
                            mstore(add(data, 0x04), from)
                            mstore(add(data, 0x24), to)
                            mstore(add(data, 0x44), amount)
                            calldatacopy(add(data, 0x64), input.offset, input.length)
                            let status := call(gas(), asset, 0, data, add(0x64, input.length), 0x0, 0x20)
                            success := and(status, or(iszero(returndatasize()), and(gt(returndatasize(), 31), eq(mload(0), 1))))
                        }
                    }
                
                    function _getMakingAmount(
                        bytes calldata getter,
                        uint256 orderTakingAmount,
                        uint256 requestedTakingAmount,
                        uint256 orderMakingAmount,
                        uint256 remainingMakingAmount,
                        bytes32 orderHash
                    ) private view returns(uint256) {
                        if (getter.length == 0) {
                            // Linear proportion
                            return AmountCalculator.getMakingAmount(orderMakingAmount, orderTakingAmount, requestedTakingAmount);
                        }
                        return _callGetter(getter, orderTakingAmount, requestedTakingAmount, orderMakingAmount, remainingMakingAmount, orderHash);
                    }
                
                    function _getTakingAmount(
                        bytes calldata getter,
                        uint256 orderMakingAmount,
                        uint256 requestedMakingAmount,
                        uint256 orderTakingAmount,
                        uint256 remainingMakingAmount,
                        bytes32 orderHash
                    ) private view returns(uint256) {
                        if (getter.length == 0) {
                            // Linear proportion
                            return AmountCalculator.getTakingAmount(orderMakingAmount, orderTakingAmount, requestedMakingAmount);
                        }
                        return _callGetter(getter, orderMakingAmount, requestedMakingAmount, orderTakingAmount, remainingMakingAmount, orderHash);
                    }
                
                    function _callGetter(
                        bytes calldata getter,
                        uint256 orderExpectedAmount,
                        uint256 requestedAmount,
                        uint256 orderResultAmount,
                        uint256 remainingMakingAmount,
                        bytes32 orderHash
                    ) private view returns(uint256) {
                        if (getter.length == 1) {
                            if (OrderLib.getterIsFrozen(getter)) {
                                // On "x" getter calldata only exact amount is allowed
                                if (requestedAmount != orderExpectedAmount) revert WrongAmount();
                                return orderResultAmount;
                            } else {
                                revert WrongGetter();
                            }
                        } else {
                            (address target, bytes calldata data) = getter.decodeTargetAndCalldata();
                            (bool success, bytes memory result) = target.staticcall(abi.encodePacked(data, requestedAmount, remainingMakingAmount, orderHash));
                            if (!success || result.length != 32) revert GetAmountCallFailed();
                            return abi.decode(result, (uint256));
                        }
                    }
                }
                
                
                // File @openzeppelin/contracts/utils/[email protected]
                
                // 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;
                    }
                }
                
                
                // File @openzeppelin/contracts/access/[email protected]
                
                // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
                
                pragma solidity ^0.8.0;
                
                /**
                 * @dev Contract module which provides a basic access control mechanism, where
                 * there is an account (an owner) that can be granted exclusive access to
                 * specific functions.
                 *
                 * By default, the owner account will be the one that deploys the contract. This
                 * can later be changed with {transferOwnership}.
                 *
                 * This module is used through inheritance. It will make available the modifier
                 * `onlyOwner`, which can be applied to your functions to restrict their use to
                 * the owner.
                 */
                abstract contract Ownable is Context {
                    address private _owner;
                
                    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                
                    /**
                     * @dev Initializes the contract setting the deployer as the initial owner.
                     */
                    constructor() {
                        _transferOwnership(_msgSender());
                    }
                
                    /**
                     * @dev Throws if called by any account other than the owner.
                     */
                    modifier onlyOwner() {
                        _checkOwner();
                        _;
                    }
                
                    /**
                     * @dev Returns the address of the current owner.
                     */
                    function owner() public view virtual returns (address) {
                        return _owner;
                    }
                
                    /**
                     * @dev Throws if the sender is not the owner.
                     */
                    function _checkOwner() internal view virtual {
                        require(owner() == _msgSender(), "Ownable: caller is not the owner");
                    }
                
                    /**
                     * @dev Leaves the contract without owner. It will not be possible to call
                     * `onlyOwner` functions anymore. Can only be called by the current owner.
                     *
                     * NOTE: Renouncing ownership will leave the contract without an owner,
                     * thereby removing any functionality that is only available to the owner.
                     */
                    function renounceOwnership() public virtual onlyOwner {
                        _transferOwnership(address(0));
                    }
                
                    /**
                     * @dev Transfers ownership of the contract to a new account (`newOwner`).
                     * Can only be called by the current owner.
                     */
                    function transferOwnership(address newOwner) public virtual onlyOwner {
                        require(newOwner != address(0), "Ownable: new owner is the zero address");
                        _transferOwnership(newOwner);
                    }
                
                    /**
                     * @dev Transfers ownership of the contract to a new account (`newOwner`).
                     * Internal function without access restriction.
                     */
                    function _transferOwnership(address newOwner) internal virtual {
                        address oldOwner = _owner;
                        _owner = newOwner;
                        emit OwnershipTransferred(oldOwner, newOwner);
                    }
                }
                
                
                // File contracts/AggregationRouterV5.sol
                
                
                pragma solidity 0.8.17;
                
                
                
                
                
                
                
                
                
                /// @notice Main contract incorporates a number of routers to perform swaps and limit orders protocol to fill limit orders
                contract AggregationRouterV5 is EIP712("1inch Aggregation Router", "5"), Ownable,
                    ClipperRouter, GenericRouter, UnoswapRouter, UnoswapV3Router, OrderMixin, OrderRFQMixin
                {
                    using UniERC20 for IERC20;
                
                    error ZeroAddress();
                
                    /**
                     * @dev Sets the wrapped eth token and clipper exhange interface
                     * Both values are immutable: they can only be set once during
                     * construction.
                     */
                    constructor(IWETH weth)
                        UnoswapV3Router(weth)
                        ClipperRouter(weth)
                        OrderMixin(weth)
                        OrderRFQMixin(weth)
                    {
                        if (address(weth) == address(0)) revert ZeroAddress();
                    }
                
                    /**
                     * @notice Retrieves funds accidently sent directly to the contract address
                     * @param token ERC20 token to retrieve
                     * @param amount amount to retrieve
                     */
                    function rescueFunds(IERC20 token, uint256 amount) external onlyOwner {
                        token.uniTransfer(payable(msg.sender), amount);
                    }
                
                    /**
                     * @notice Destroys the contract and sends eth to sender. Use with caution.
                     * The only case when the use of the method is justified is if there is an exploit found.
                     * And the damage from the exploit is greater than from just an urgent contract change.
                     */
                    function destroy() external onlyOwner {
                        selfdestruct(payable(msg.sender));
                    }
                
                    function _receive() internal override(EthReceiver, OnlyWethReceiver) {
                        EthReceiver._receive();
                    }
                }

                File 2 of 5: FRAXShares
                {"AccessControl.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.6.0;\n\nimport \"./EnumerableSet.sol\";\nimport \"./Address.sol\";\nimport \"./Context.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n *     require(hasRole(MY_ROLE, msg.sender));\n *     ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role\u0027s admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context {\n    using EnumerableSet for EnumerableSet.AddressSet;\n    using Address for address;\n\n    struct RoleData {\n        EnumerableSet.AddressSet members;\n        bytes32 adminRole;\n    }\n\n    mapping (bytes32 =\u003e RoleData) private _roles;\n\n    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; //bytes32(uint256(0x4B437D01b575618140442A4975db38850e3f8f5f) \u003c\u003c 96);\n\n    /**\n     * @dev Emitted when `newAdminRole` is set as ``role``\u0027s admin role, replacing `previousAdminRole`\n     *\n     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n     * {RoleAdminChanged} not being emitted signaling this.\n     *\n     * _Available since v3.1._\n     */\n    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n    /**\n     * @dev Emitted when `account` is granted `role`.\n     *\n     * `sender` is the account that originated the contract call, an admin role\n     * bearer except when using {_setupRole}.\n     */\n    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Emitted when `account` is revoked `role`.\n     *\n     * `sender` is the account that originated the contract call:\n     *   - if using `revokeRole`, it is the admin role bearer\n     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)\n     */\n    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) public view returns (bool) {\n        return _roles[role].members.contains(account);\n    }\n\n    /**\n     * @dev Returns the number of accounts that have `role`. Can be used\n     * together with {getRoleMember} to enumerate all bearers of a role.\n     */\n    function getRoleMemberCount(bytes32 role) public view returns (uint256) {\n        return _roles[role].members.length();\n    }\n\n    /**\n     * @dev Returns one of the accounts that have `role`. `index` must be a\n     * value between 0 and {getRoleMemberCount}, non-inclusive.\n     *\n     * Role bearers are not sorted in any particular way, and their ordering may\n     * change at any point.\n     *\n     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n     * you perform all queries on the same block. See the following\n     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n     * for more information.\n     */\n    function getRoleMember(bytes32 role, uint256 index) public view returns (address) {\n        return _roles[role].members.at(index);\n    }\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role\u0027s admin, use {_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) public view returns (bytes32) {\n        return _roles[role].adminRole;\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``\u0027s admin role.\n     */\n    function grantRole(bytes32 role, address account) public virtual {\n        require(hasRole(_roles[role].adminRole, _msgSender()), \"AccessControl: sender must be an admin to grant\");\n\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``\u0027s admin role.\n     */\n    function revokeRole(bytes32 role, address account) public virtual {\n        require(hasRole(_roles[role].adminRole, _msgSender()), \"AccessControl: sender must be an admin to revoke\");\n\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function\u0027s\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been granted `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `account`.\n     */\n    function renounceRole(bytes32 role, address account) public virtual {\n        require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event. Note that unlike {grantRole}, this function doesn\u0027t perform any\n     * checks on the calling account.\n     *\n     * [WARNING]\n     * ====\n     * This function should only be called from the constructor when setting\n     * up the initial roles for the system.\n     *\n     * Using this function in any other way is effectively circumventing the admin\n     * system imposed by {AccessControl}.\n     * ====\n     */\n    function _setupRole(bytes32 role, address account) internal virtual {\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Sets `adminRole` as ``role``\u0027s admin role.\n     *\n     * Emits a {RoleAdminChanged} event.\n     */\n    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n        emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);\n        _roles[role].adminRole = adminRole;\n    }\n\n    function _grantRole(bytes32 role, address account) private {\n        if (_roles[role].members.add(account)) {\n            emit RoleGranted(role, account, _msgSender());\n        }\n    }\n\n    function _revokeRole(bytes32 role, address account) private {\n        if (_roles[role].members.remove(account)) {\n            emit RoleRevoked(role, account, _msgSender());\n        }\n    }\n}\n"},"Address.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies in extcodesize, which returns 0 for contracts in\n        // construction, since the code is only stored at the end of the\n        // constructor execution.\n\n        uint256 size;\n        // solhint-disable-next-line no-inline-assembly\n        assembly { size := extcodesize(account) }\n        return size \u003e 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity\u0027s `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance \u003e= amount, \"Address: insufficient balance\");\n\n        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n        (bool success, ) = recipient.call{ value: amount }(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain`call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n      return functionCall(target, data, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n        return _functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n        require(address(this).balance \u003e= value, \"Address: insufficient balance for call\");\n        return _functionCallWithValue(target, data, value, errorMessage);\n    }\n\n    function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {\n        require(isContract(target), \"Address: call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);\n        if (success) {\n            return returndata;\n        } else {\n            // Look for revert reason and bubble it up if present\n            if (returndata.length \u003e 0) {\n                // The easiest way to bubble the revert reason is using memory via assembly\n\n                // solhint-disable-next-line no-inline-assembly\n                assembly {\n                    let returndata_size := mload(returndata)\n                    revert(add(32, returndata), returndata_size)\n                }\n            } else {\n                revert(errorMessage);\n            }\n        }\n    }\n}"},"AggregatorV3Interface.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity \u003e=0.6.0;\n\ninterface AggregatorV3Interface {\n\n  function decimals() external view returns (uint8);\n  function description() external view returns (string memory);\n  function version() external view returns (uint256);\n\n  // getRoundData and latestRoundData should both raise \"No data present\"\n  // if they do not have data to report, instead of returning unset values\n  // which could be misinterpreted as actual reported values.\n  function getRoundData(uint80 _roundId)\n    external\n    view\n    returns (\n      uint80 roundId,\n      int256 answer,\n      uint256 startedAt,\n      uint256 updatedAt,\n      uint80 answeredInRound\n    );\n  function latestRoundData()\n    external\n    view\n    returns (\n      uint80 roundId,\n      int256 answer,\n      uint256 startedAt,\n      uint256 updatedAt,\n      uint80 answeredInRound\n    );\n\n}"},"Babylonian.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n// computes square roots using the babylonian method\n// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method\nlibrary Babylonian {\n    function sqrt(uint y) internal pure returns (uint z) {\n        if (y \u003e 3) {\n            z = y;\n            uint x = y / 2 + 1;\n            while (x \u003c z) {\n                z = x;\n                x = (y / x + x) / 2;\n            }\n        } else if (y != 0) {\n            z = 1;\n        }\n        // else z = 0\n    }\n}"},"BlockMiner.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n// file: BlockMinder.sol\n\n// used to \"waste\" blocks for truffle tests\ncontract BlockMiner {\n    uint256 public blocksMined;\n\n    constructor () public {\n        blocksMined = 0;\n    }\n\n    function mine() public {\n       blocksMined += 1;\n    }\n\n    function blockTime() external view returns (uint256) {\n       return block.timestamp;\n    }\n}"},"ChainlinkETHUSDPriceConsumer.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./AggregatorV3Interface.sol\";\n\ncontract ChainlinkETHUSDPriceConsumer {\n\n    AggregatorV3Interface internal priceFeed;\n\n\n    constructor() public {\n        priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);\n    }\n\n    /**\n     * Returns the latest price\n     */\n    function getLatestPrice() public view returns (int) {\n        (\n            , \n            int price,\n            ,\n            ,\n            \n        ) = priceFeed.latestRoundData();\n        return price;\n    }\n\n    function getDecimals() public view returns (uint8) {\n        return priceFeed.decimals();\n    }\n}"},"ChainlinkETHUSDPriceConsumerTest.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./AggregatorV3Interface.sol\";\n\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// import \"@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol\";\n\ncontract ChainlinkETHUSDPriceConsumerTest {\n\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // AggregatorV3Interface internal priceFeed;\n\n    /**\n     * Network: Kovan\n     * Aggregator: ETH/USD\n     * Address: 0x9326BFA02ADD2366b30bacB125260Af641031331\n     */\n    /**\n     * Network: Mainnet\n     * Aggregator: ETH/USD\n     * Address: 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419\n     */\n\n     \n    constructor() public {\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);\n    }\n\n    /**\n     * Returns the latest price\n     */\n    function getLatestPrice() public pure returns (int) {\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // (\n        //     uint80 roundID, \n        //     int price,\n        //     uint startedAt,\n        //     uint timeStamp,\n        //     uint80 answeredInRound\n        // ) = priceFeed.latestRoundData();\n        // // If the round is not complete yet, timestamp is 0\n        // require(timeStamp \u003e 0, \"Round not complete\");\n\n        // This will return something like 32063000000\n        // Divide this by getDecimals to get the \"true\" price\n        // You can can multiply the \"true\" price by 1e6 to get the frax ecosystem \u0027price\u0027\n        // return price;\n\n        return 59000000000;\n    }\n\n    function getDecimals() public pure returns (uint8) {\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // return priceFeed.decimals();\n        return 8;\n    }\n}"},"Context.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\ncontract Context {\n    // Empty internal constructor, to prevent people from mistakenly deploying\n    // an instance of this contract, which should be used via inheritance.\n    constructor () internal { }\n\n    function _msgSender() internal view virtual returns (address payable) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes memory) {\n        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n        return msg.data;\n    }\n}"},"EnumerableSet.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.6.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`\n * (`UintSet`) are supported.\n */\nlibrary EnumerableSet {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n\n        // Position of the value in the `values` array, plus 1 because index 0\n        // means a value is not in the set.\n        mapping (bytes32 =\u003e uint256) _indexes;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._indexes[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We read and store the value\u0027s index to prevent multiple reads from the same storage slot\n        uint256 valueIndex = set._indexes[value];\n\n        if (valueIndex != 0) { // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as \u0027swap and pop\u0027).\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 toDeleteIndex = valueIndex - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs\n            // so rarely, we still do the swap anyway to avoid the gas cost of adding an \u0027if\u0027 statement.\n\n            bytes32 lastvalue = set._values[lastIndex];\n\n            // Move the last value to the index where the value to delete is\n            set._values[toDeleteIndex] = lastvalue;\n            // Update the index for the moved value\n            set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the index for the deleted slot\n            delete set._indexes[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._indexes[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n   /**\n    * @dev Returns the value stored at position `index` in the set. O(1).\n    *\n    * Note that there are no guarantees on the ordering of values inside the\n    * array, and it may change when more values are added or removed.\n    *\n    * Requirements:\n    *\n    * - `index` must be strictly less than {length}.\n    */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        require(set._values.length \u003e index, \"EnumerableSet: index out of bounds\");\n        return set._values[index];\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(value)));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(value)));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(value)));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n   /**\n    * @dev Returns the value stored at position `index` in the set. O(1).\n    *\n    * Note that there are no guarantees on the ordering of values inside the\n    * array, and it may change when more values are added or removed.\n    *\n    * Requirements:\n    *\n    * - `index` must be strictly less than {length}.\n    */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint256(_at(set._inner, index)));\n    }\n\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n   /**\n    * @dev Returns the value stored at position `index` in the set. O(1).\n    *\n    * Note that there are no guarantees on the ordering of values inside the\n    * array, and it may change when more values are added or removed.\n    *\n    * Requirements:\n    *\n    * - `index` must be strictly less than {length}.\n    */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n}\n"},"ERC20.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./Context.sol\";\nimport \"./IERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./Address.sol\";\n\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20Mintable}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn\u0027t required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\n \ncontract ERC20 is Context, IERC20 {\n    using SafeMath for uint256;\n\n    mapping (address =\u003e uint256) private _balances;\n\n    mapping (address =\u003e mapping (address =\u003e uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n    uint8 private _decimals;\n    \n    /**\n     * @dev Sets the values for {name} and {symbol}, initializes {decimals} with\n     * a default value of 18.\n     *\n     * To select a different value for {decimals}, use {_setupDecimals}.\n     *\n     * All three of these values are immutable: they can only be set once during\n     * construction.\n     */\n    constructor (string memory name, string memory symbol) public {\n        _name = name;\n        _symbol = symbol;\n        _decimals = 18;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5,05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is\n     * called.\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view returns (uint8) {\n        return _decimals;\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view override returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `recipient` cannot be the zero address.\n     * - the caller must have a balance of at least `amount`.\n     */\n    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(_msgSender(), recipient, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.approve(address spender, uint256 amount)\n     */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        _approve(_msgSender(), spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20};\n     *\n     * Requirements:\n     * - `sender` and `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     * - the caller must have allowance for `sender`\u0027s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(sender, recipient, amount);\n        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n        return true;\n    }\n\n    /**\n     * @dev Moves tokens `amount` from `sender` to `recipient`.\n     *\n     * This is internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * Requirements:\n     *\n     * - `sender` cannot be the zero address.\n     * - `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     */\n    function _transfer(address sender, address recipient, uint256 amount) internal virtual {\n        require(sender != address(0), \"ERC20: transfer from the zero address\");\n        require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(sender, recipient, amount);\n\n        _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n        _balances[recipient] = _balances[recipient].add(amount);\n        emit Transfer(sender, recipient, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements\n     *\n     * - `to` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply = _totalSupply.add(amount);\n        _balances[account] = _balances[account].add(amount);\n        emit Transfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from the caller.\n     *\n     * See {ERC20-_burn}.\n     */\n    function burn(uint256 amount) public virtual {\n        _burn(_msgSender(), amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, deducting from the caller\u0027s\n     * allowance.\n     *\n     * See {ERC20-_burn} and {ERC20-allowance}.\n     *\n     * Requirements:\n     *\n     * - the caller must have allowance for `accounts`\u0027s tokens of at least\n     * `amount`.\n     */\n    function burnFrom(address account, uint256 amount) public virtual {\n        uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, \"ERC20: burn amount exceeds allowance\");\n\n        _approve(account, _msgSender(), decreasedAllowance);\n        _burn(account, amount);\n    }\n\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n        _totalSupply = _totalSupply.sub(amount);\n        emit Transfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.\n     *\n     * This is internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     */\n    function _approve(address owner, address spender, uint256 amount) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`.`amount` is then deducted\n     * from the caller\u0027s allowance.\n     *\n     * See {_burn} and {_approve}.\n     */\n    function _burnFrom(address account, uint256 amount) internal virtual {\n        _burn(account, amount);\n        _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, \"ERC20: burn amount exceeds allowance\"));\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of `from`\u0027s tokens\n     * will be to transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of `from`\u0027s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks].\n     */\n    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }\n}\n"},"ERC20Custom.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./Context.sol\";\nimport \"./IERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./Address.sol\";\n\n// Due to compiling issues, _name, _symbol, and _decimals were removed\n\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20Mintable}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn\u0027t required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20Custom is Context, IERC20 {\n    using SafeMath for uint256;\n\n    mapping (address =\u003e uint256) internal _balances;\n\n    mapping (address =\u003e mapping (address =\u003e uint256)) internal _allowances;\n\n    uint256 private _totalSupply;\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view override returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `recipient` cannot be the zero address.\n     * - the caller must have a balance of at least `amount`.\n     */\n    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(_msgSender(), recipient, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.approve(address spender, uint256 amount)\n     */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        _approve(_msgSender(), spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20};\n     *\n     * Requirements:\n     * - `sender` and `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     * - the caller must have allowance for `sender`\u0027s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(sender, recipient, amount);\n        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n        return true;\n    }\n\n    /**\n     * @dev Moves tokens `amount` from `sender` to `recipient`.\n     *\n     * This is internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * Requirements:\n     *\n     * - `sender` cannot be the zero address.\n     * - `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     */\n    function _transfer(address sender, address recipient, uint256 amount) internal virtual {\n        require(sender != address(0), \"ERC20: transfer from the zero address\");\n        require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(sender, recipient, amount);\n\n        _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n        _balances[recipient] = _balances[recipient].add(amount);\n        emit Transfer(sender, recipient, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements\n     *\n     * - `to` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply = _totalSupply.add(amount);\n        _balances[account] = _balances[account].add(amount);\n        emit Transfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from the caller.\n     *\n     * See {ERC20-_burn}.\n     */\n    function burn(uint256 amount) public virtual {\n        _burn(_msgSender(), amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, deducting from the caller\u0027s\n     * allowance.\n     *\n     * See {ERC20-_burn} and {ERC20-allowance}.\n     *\n     * Requirements:\n     *\n     * - the caller must have allowance for `accounts`\u0027s tokens of at least\n     * `amount`.\n     */\n    function burnFrom(address account, uint256 amount) public virtual {\n        uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, \"ERC20: burn amount exceeds allowance\");\n\n        _approve(account, _msgSender(), decreasedAllowance);\n        _burn(account, amount);\n    }\n\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n        _totalSupply = _totalSupply.sub(amount);\n        emit Transfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.\n     *\n     * This is internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     */\n    function _approve(address owner, address spender, uint256 amount) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`.`amount` is then deducted\n     * from the caller\u0027s allowance.\n     *\n     * See {_burn} and {_approve}.\n     */\n    function _burnFrom(address account, uint256 amount) internal virtual {\n        _burn(account, amount);\n        _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, \"ERC20: burn amount exceeds allowance\"));\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of `from`\u0027s tokens\n     * will be to transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of `from`\u0027s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks].\n     */\n    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }\n}"},"FakeCollateral.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./Context.sol\";\nimport \"./IERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./Address.sol\";\n\n// Due to compiling issues, _name, _symbol, and _decimals were removed\n\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20Mintable}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn\u0027t required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract FakeCollateral is Context, IERC20 {\n    using SafeMath for uint256;\n    string public symbol;\n    uint8 public decimals;\n    address public creator_address;\n    uint256 public genesis_supply;\n    uint256 private _totalSupply;\n\n    mapping (address =\u003e uint256) private _balances;\n    mapping (address =\u003e mapping (address =\u003e uint256)) private _allowances;\n    mapping (address =\u003e bool) used;\n\n    constructor(\n        address _creator_address,\n        uint256 _genesis_supply,\n        string memory _symbol,\n        uint8 _decimals\n    ) public {\n        genesis_supply = _genesis_supply;\n        creator_address = _creator_address;\n        symbol = _symbol;\n        decimals = _decimals;\n        _mint(creator_address, genesis_supply);\n    }\n\n    function faucet() public {\n    \tif (used[msg.sender] == false) {\n    \t\tused[msg.sender] = true;\n    \t\t_mint(msg.sender, 1000 * (10 ** uint256(decimals)));\n    \t}\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view override returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `recipient` cannot be the zero address.\n     * - the caller must have a balance of at least `amount`.\n     */\n    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(_msgSender(), recipient, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.approve(address spender, uint256 amount)\n     */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        _approve(_msgSender(), spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20};\n     *\n     * Requirements:\n     * - `sender` and `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     * - the caller must have allowance for `sender`\u0027s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(sender, recipient, amount);\n        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n        return true;\n    }\n\n    /**\n     * @dev Moves tokens `amount` from `sender` to `recipient`.\n     *\n     * This is internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * Requirements:\n     *\n     * - `sender` cannot be the zero address.\n     * - `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     */\n    function _transfer(address sender, address recipient, uint256 amount) internal virtual {\n        require(sender != address(0), \"ERC20: transfer from the zero address\");\n        require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(sender, recipient, amount);\n\n        _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n        _balances[recipient] = _balances[recipient].add(amount);\n        emit Transfer(sender, recipient, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements\n     *\n     * - `to` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply = _totalSupply.add(amount);\n        _balances[account] = _balances[account].add(amount);\n        emit Transfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from the caller.\n     *\n     * See {ERC20-_burn}.\n     */\n    function burn(uint256 amount) public virtual {\n        _burn(_msgSender(), amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, deducting from the caller\u0027s\n     * allowance.\n     *\n     * See {ERC20-_burn} and {ERC20-allowance}.\n     *\n     * Requirements:\n     *\n     * - the caller must have allowance for `accounts`\u0027s tokens of at least\n     * `amount`.\n     */\n    function burnFrom(address account, uint256 amount) public virtual {\n        uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, \"ERC20: burn amount exceeds allowance\");\n\n        _approve(account, _msgSender(), decreasedAllowance);\n        _burn(account, amount);\n    }\n\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n        _totalSupply = _totalSupply.sub(amount);\n        emit Transfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.\n     *\n     * This is internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     */\n    function _approve(address owner, address spender, uint256 amount) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`.`amount` is then deducted\n     * from the caller\u0027s allowance.\n     *\n     * See {_burn} and {_approve}.\n     */\n    function _burnFrom(address account, uint256 amount) internal virtual {\n        _burn(account, amount);\n        _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, \"ERC20: burn amount exceeds allowance\"));\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of `from`\u0027s tokens\n     * will be to transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of `from`\u0027s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks].\n     */\n    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }\n}\n"},"FakeCollateral_USDC.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./FakeCollateral.sol\";\n\ncontract FakeCollateral_USDC is FakeCollateral {\n    constructor(\n        address _creator_address,\n        uint256 _genesis_supply,\n        string memory _symbol,\n        uint8 _decimals\n    ) \n    FakeCollateral(_creator_address, _genesis_supply, _symbol, _decimals)\n    public {}\n}"},"FakeCollateral_USDT.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./FakeCollateral.sol\";\n\ncontract FakeCollateral_USDT is FakeCollateral {\n    constructor(\n        address _creator_address,\n        uint256 _genesis_supply,\n        string memory _symbol,\n        uint8 _decimals\n    ) \n    FakeCollateral(_creator_address, _genesis_supply, _symbol, _decimals)\n    public {}\n}"},"FakeCollateral_WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./FakeCollateral.sol\";\n\ncontract FakeCollateral_WETH is FakeCollateral {\n    constructor(\n        address _creator_address,\n        uint256 _genesis_supply,\n        string memory _symbol,\n        uint8 _decimals\n    ) \n    FakeCollateral(_creator_address, _genesis_supply, _symbol, _decimals)\n    public {}\n}"},"FixedPoint.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./Babylonian.sol\u0027;\n\n// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))\nlibrary FixedPoint {\n    // range: [0, 2**112 - 1]\n    // resolution: 1 / 2**112\n    struct uq112x112 {\n        uint224 _x;\n    }\n\n    // range: [0, 2**144 - 1]\n    // resolution: 1 / 2**112\n    struct uq144x112 {\n        uint _x;\n    }\n\n    uint8 private constant RESOLUTION = 112;\n    uint private constant Q112 = uint(1) \u003c\u003c RESOLUTION;\n    uint private constant Q224 = Q112 \u003c\u003c RESOLUTION;\n\n    // encode a uint112 as a UQ112x112\n    function encode(uint112 x) internal pure returns (uq112x112 memory) {\n        return uq112x112(uint224(x) \u003c\u003c RESOLUTION);\n    }\n\n    // encodes a uint144 as a UQ144x112\n    function encode144(uint144 x) internal pure returns (uq144x112 memory) {\n        return uq144x112(uint256(x) \u003c\u003c RESOLUTION);\n    }\n\n    // divide a UQ112x112 by a uint112, returning a UQ112x112\n    function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {\n        require(x != 0, \u0027FixedPoint: DIV_BY_ZERO\u0027);\n        return uq112x112(self._x / uint224(x));\n    }\n\n    // multiply a UQ112x112 by a uint, returning a UQ144x112\n    // reverts on overflow\n    function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {\n        uint z;\n        require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), \"FixedPoint: MULTIPLICATION_OVERFLOW\");\n        return uq144x112(z);\n    }\n\n    // returns a UQ112x112 which represents the ratio of the numerator to the denominator\n    // equivalent to encode(numerator).div(denominator)\n    function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {\n        require(denominator \u003e 0, \"FixedPoint: DIV_BY_ZERO\");\n        return uq112x112((uint224(numerator) \u003c\u003c RESOLUTION) / denominator);\n    }\n\n    // decode a UQ112x112 into a uint112 by truncating after the radix point\n    function decode(uq112x112 memory self) internal pure returns (uint112) {\n        return uint112(self._x \u003e\u003e RESOLUTION);\n    }\n\n    // decode a UQ144x112 into a uint144 by truncating after the radix point\n    function decode144(uq144x112 memory self) internal pure returns (uint144) {\n        return uint144(self._x \u003e\u003e RESOLUTION);\n    }\n\n    // take the reciprocal of a UQ112x112\n    function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {\n        require(self._x != 0, \u0027FixedPoint: ZERO_RECIPROCAL\u0027);\n        return uq112x112(uint224(Q224 / self._x));\n    }\n\n    // square root of a UQ112x112\n    function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {\n        return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) \u003c\u003c 56));\n    }\n}"},"Frax.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./Context.sol\";\nimport \"./IERC20.sol\";\nimport \"./ERC20Custom.sol\";\nimport \"./ERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./FXS.sol\";\nimport \"./FraxPool.sol\";\nimport \"./UniswapPairOracle.sol\";\nimport \"./ChainlinkETHUSDPriceConsumer.sol\";\nimport \"./AccessControl.sol\";\n\ncontract FRAXStablecoin is ERC20Custom, AccessControl {\n    using SafeMath for uint256;\n\n    /* ========== STATE VARIABLES ========== */\n    enum PriceChoice { FRAX, FXS }\n    ChainlinkETHUSDPriceConsumer private eth_usd_pricer;\n    uint8 private eth_usd_pricer_decimals;\n    UniswapPairOracle private fraxEthOracle;\n    UniswapPairOracle private fxsEthOracle;\n    string public symbol;\n    string public name;\n    uint8 public constant decimals = 18;\n    address public owner_address;\n    address public creator_address;\n    address public timelock_address; // Governance timelock address\n    address public controller_address; // Controller contract to dynamically adjust system parameters automatically\n    address public fxs_address;\n    address public frax_eth_oracle_address;\n    address public fxs_eth_oracle_address;\n    address public weth_address;\n    address public eth_usd_consumer_address;\n    uint256 public constant genesis_supply = 2000000e18; // 2M FRAX (only for testing, genesis supply will be 5k on Mainnet). This is to help with establishing the Uniswap pools, as they need liquidity\n\n    // The addresses in this array are added by the oracle and these contracts are able to mint frax\n    address[] public frax_pools_array;\n\n    // Mapping is also used for faster verification\n    mapping(address =\u003e bool) public frax_pools; \n\n    // Constants for various precisions\n    uint256 private constant PRICE_PRECISION = 1e6;\n    \n    uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102\n    uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee\n    uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee\n    uint256 public frax_step; // Amount to change the collateralization ratio by upon refreshCollateralRatio()\n    uint256 public refresh_cooldown; // Seconds to wait before being able to run refreshCollateralRatio() again\n    uint256 public price_target; // The price of FRAX at which the collateral ratio will respond to; this value is only used for the collateral ratio mechanism and not for minting and redeeming which are hardcoded at $1\n    uint256 public price_band; // The bound above and below the price target at which the refreshCollateralRatio() will not change the collateral ratio\n\n    address public DEFAULT_ADMIN_ADDRESS;\n    bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256(\"COLLATERAL_RATIO_PAUSER\");\n    bool public collateral_ratio_paused = false;\n\n    /* ========== MODIFIERS ========== */\n\n    modifier onlyCollateralRatioPauser() {\n        require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender));\n        _;\n    }\n\n    modifier onlyPools() {\n       require(frax_pools[msg.sender] == true, \"Only frax pools can call this function\");\n        _;\n    } \n    \n    modifier onlyByOwnerOrGovernance() {\n        require(msg.sender == owner_address || msg.sender == timelock_address || msg.sender == controller_address, \"You are not the owner, controller, or the governance timelock\");\n        _;\n    }\n\n    modifier onlyByOwnerGovernanceOrPool() {\n        require(\n            msg.sender == owner_address \n            || msg.sender == timelock_address \n            || frax_pools[msg.sender] == true, \n            \"You are not the owner, the governance timelock, or a pool\");\n        _;\n    }\n\n    /* ========== CONSTRUCTOR ========== */\n\n    constructor(\n        string memory _name,\n        string memory _symbol,\n        address _creator_address,\n        address _timelock_address\n    ) public {\n        name = _name;\n        symbol = _symbol;\n        creator_address = _creator_address;\n        timelock_address = _timelock_address;\n        _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n        DEFAULT_ADMIN_ADDRESS = _msgSender();\n        owner_address = _creator_address;\n        _mint(creator_address, genesis_supply);\n        grantRole(COLLATERAL_RATIO_PAUSER, creator_address);\n        grantRole(COLLATERAL_RATIO_PAUSER, timelock_address);\n        frax_step = 2500; // 6 decimals of precision, equal to 0.25%\n        global_collateral_ratio = 1000000; // Frax system starts off fully collateralized (6 decimals of precision)\n        refresh_cooldown = 3600; // Refresh cooldown period is set to 1 hour (3600 seconds) at genesis\n        price_target = 1000000; // Collateral ratio will adjust according to the $1 price target at genesis\n        price_band = 5000; // Collateral ratio will not adjust if between $0.995 and $1.005 at genesis\n    }\n\n    /* ========== VIEWS ========== */\n\n    // Choice = \u0027FRAX\u0027 or \u0027FXS\u0027 for now\n    function oracle_price(PriceChoice choice) internal view returns (uint256) {\n        // Get the ETH / USD price first, and cut it down to 1e6 precision\n        uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);\n        uint256 price_vs_eth;\n\n        if (choice == PriceChoice.FRAX) {\n            price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH\n        }\n        else if (choice == PriceChoice.FXS) {\n            price_vs_eth = uint256(fxsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FXS if you put in PRICE_PRECISION WETH\n        }\n        else revert(\"INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)\");\n\n        // Will be in 1e6 format\n        return eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth);\n    }\n\n    // Returns X FRAX = 1 USD\n    function frax_price() public view returns (uint256) {\n        return oracle_price(PriceChoice.FRAX);\n    }\n\n    // Returns X FXS = 1 USD\n    function fxs_price()  public view returns (uint256) {\n        return oracle_price(PriceChoice.FXS);\n    }\n\n    function eth_usd_price() public view returns (uint256) {\n        return uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);\n    }\n\n    // This is needed to avoid costly repeat calls to different getter functions\n    // It is cheaper gas-wise to just dump everything and only use some of the info\n    function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {\n        return (\n            oracle_price(PriceChoice.FRAX), // frax_price()\n            oracle_price(PriceChoice.FXS), // fxs_price()\n            totalSupply(), // totalSupply()\n            global_collateral_ratio, // global_collateral_ratio()\n            globalCollateralValue(), // globalCollateralValue\n            minting_fee, // minting_fee()\n            redemption_fee, // redemption_fee()\n            uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price\n        );\n    }\n\n    // Iterate through all frax pools and calculate all value of collateral in all pools globally \n    function globalCollateralValue() public view returns (uint256) {\n        uint256 total_collateral_value_d18 = 0; \n\n        for (uint i = 0; i \u003c frax_pools_array.length; i++){ \n            // Exclude null addresses\n            if (frax_pools_array[i] != address(0)){\n                total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance());\n            }\n\n        }\n        return total_collateral_value_d18;\n    }\n\n    /* ========== PUBLIC FUNCTIONS ========== */\n    \n    // There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion.\n    uint256 public last_call_time; // Last time the refreshCollateralRatio function was called\n    function refreshCollateralRatio() public {\n        require(collateral_ratio_paused == false, \"Collateral Ratio has been paused\");\n        uint256 frax_price_cur = frax_price();\n        require(block.timestamp - last_call_time \u003e= refresh_cooldown, \"Must wait for the refresh cooldown since last refresh\");\n\n        // Step increments are 0.25% (upon genesis, changable by setFraxStep()) \n        \n        if (frax_price_cur \u003e price_target.add(price_band)) { //decrease collateral ratio\n            if(global_collateral_ratio \u003c= frax_step){ //if within a step of 0, go to 0\n                global_collateral_ratio = 0;\n            } else {\n                global_collateral_ratio = global_collateral_ratio.sub(frax_step);\n            }\n        } else if (frax_price_cur \u003c price_target.sub(price_band)) { //increase collateral ratio\n            if(global_collateral_ratio.add(frax_step) \u003e= 1000000){\n                global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000\n            } else {\n                global_collateral_ratio = global_collateral_ratio.add(frax_step);\n            }\n        }\n\n        last_call_time = block.timestamp; // Set the time of the last expansion\n    }\n\n    /* ========== RESTRICTED FUNCTIONS ========== */\n\n    // Used by pools when user redeems\n    function pool_burn_from(address b_address, uint256 b_amount) public onlyPools {\n        super._burnFrom(b_address, b_amount);\n        emit FRAXBurned(b_address, msg.sender, b_amount);\n    }\n\n    // This function is what other frax pools will call to mint new FRAX \n    function pool_mint(address m_address, uint256 m_amount) public onlyPools {\n        super._mint(m_address, m_amount);\n        emit FRAXMinted(msg.sender, m_address, m_amount);\n    }\n\n    // Adds collateral addresses supported, such as tether and busd, must be ERC20 \n    function addPool(address pool_address) public onlyByOwnerOrGovernance {\n        require(frax_pools[pool_address] == false, \"address already exists\");\n        frax_pools[pool_address] = true; \n        frax_pools_array.push(pool_address);\n    }\n\n    // Remove a pool \n    function removePool(address pool_address) public onlyByOwnerOrGovernance {\n        require(frax_pools[pool_address] == true, \"address doesn\u0027t exist already\");\n        \n        // Delete from the mapping\n        delete frax_pools[pool_address];\n\n        // \u0027Delete\u0027 from the array by setting the address to 0x0\n        for (uint i = 0; i \u003c frax_pools_array.length; i++){ \n            if (frax_pools_array[i] == pool_address) {\n                frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same\n                break;\n            }\n        }\n    }\n\n    function setOwner(address _owner_address) external onlyByOwnerOrGovernance {\n        owner_address = _owner_address;\n    }\n\n    function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance {\n        redemption_fee = red_fee;\n    }\n\n    function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance {\n        minting_fee = min_fee;\n    }  \n\n    function setFraxStep(uint256 _new_step) public onlyByOwnerOrGovernance {\n        frax_step = _new_step;\n    }  \n\n    function setPriceTarget (uint256 _new_price_target) public onlyByOwnerOrGovernance {\n        price_target = _new_price_target;\n    }\n\n    function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerOrGovernance {\n    \trefresh_cooldown = _new_cooldown;\n    }\n\n    function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance {\n        fxs_address = _fxs_address;\n    }\n\n    function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance {\n        eth_usd_consumer_address = _eth_usd_consumer_address;\n        eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address);\n        eth_usd_pricer_decimals = eth_usd_pricer.getDecimals();\n    }\n\n    function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {\n        timelock_address = new_timelock;\n    }\n\n    function setController(address _controller_address) external onlyByOwnerOrGovernance {\n        controller_address = _controller_address;\n    }\n\n    function setPriceBand(uint256 _price_band) external onlyByOwnerOrGovernance {\n        price_band = _price_band;\n    }\n\n    // Sets the FRAX_ETH Uniswap oracle address \n    function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance {\n        frax_eth_oracle_address = _frax_oracle_addr;\n        fraxEthOracle = UniswapPairOracle(_frax_oracle_addr); \n        weth_address = _weth_address;\n    }\n\n    // Sets the FXS_ETH Uniswap oracle address \n    function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance {\n        fxs_eth_oracle_address = _fxs_oracle_addr;\n        fxsEthOracle = UniswapPairOracle(_fxs_oracle_addr);\n        weth_address = _weth_address;\n    }\n\n    function toggleCollateralRatio() public onlyCollateralRatioPauser {\n        collateral_ratio_paused = !collateral_ratio_paused;\n    }\n\n    /* ========== EVENTS ========== */\n\n    // Track FRAX burned\n    event FRAXBurned(address indexed from, address indexed to, uint256 amount);\n\n    // Track FRAX minted\n    event FRAXMinted(address indexed from, address indexed to, uint256 amount);\n}\n"},"FraxPool.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./SafeMath.sol\";\nimport \"./FXS.sol\";\nimport \"./Frax.sol\";\nimport \"./ERC20.sol\";\n// import \u0027../../Uniswap/TransferHelper.sol\u0027;\nimport \"./UniswapPairOracle.sol\";\nimport \"./AccessControl.sol\";\n// import \"../../Utils/StringHelpers.sol\";\nimport \"./FraxPoolLibrary.sol\";\n\n/*\n   Same as FraxPool.sol, but has some gas optimizations\n*/\n\n\ncontract FraxPool is AccessControl {\n    using SafeMath for uint256;\n\n    /* ========== STATE VARIABLES ========== */\n\n    ERC20 private collateral_token;\n    address private collateral_address;\n    address private owner_address;\n    // address private oracle_address;\n    address private frax_contract_address;\n    address private fxs_contract_address;\n    address private timelock_address; // Timelock address for the governance contract\n    FRAXShares private FXS;\n    FRAXStablecoin private FRAX;\n    // UniswapPairOracle private oracle;\n    UniswapPairOracle private collatEthOracle;\n    address private collat_eth_oracle_address;\n    address private weth_address;\n\n    uint256 private minting_fee;\n    uint256 private redemption_fee;\n\n    mapping (address =\u003e uint256) public redeemFXSBalances;\n    mapping (address =\u003e uint256) public redeemCollateralBalances;\n    uint256 public unclaimedPoolCollateral;\n    uint256 public unclaimedPoolFXS;\n    mapping (address =\u003e uint256) public lastRedeemed;\n\n    // Constants for various precisions\n    uint256 private constant PRICE_PRECISION = 1e6;\n    uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6;\n    uint256 private constant COLLATERAL_RATIO_MAX = 1e6;\n\n    // Number of decimals needed to get to 18\n    uint256 private missing_decimals;\n    \n    // Pool_ceiling is the total units of collateral that a pool contract can hold\n    uint256 public pool_ceiling = 0;\n\n    // Stores price of the collateral, if price is paused\n    uint256 public pausedPrice = 0;\n\n    // Bonus rate on FXS minted during recollateralizeFRAX(); 6 decimals of precision, set to 0.75% on genesis\n    uint256 public bonus_rate = 7500;\n\n    // Number of blocks to wait before being able to collectRedemption()\n    uint256 public redemption_delay = 1;\n\n    // AccessControl Roles\n    bytes32 private constant MINT_PAUSER = keccak256(\"MINT_PAUSER\");\n    bytes32 private constant REDEEM_PAUSER = keccak256(\"REDEEM_PAUSER\");\n    bytes32 private constant BUYBACK_PAUSER = keccak256(\"BUYBACK_PAUSER\");\n    bytes32 private constant RECOLLATERALIZE_PAUSER = keccak256(\"RECOLLATERALIZE_PAUSER\");\n    bytes32 private constant COLLATERAL_PRICE_PAUSER = keccak256(\"COLLATERAL_PRICE_PAUSER\");\n    \n    // AccessControl state variables\n    bool private mintPaused = false;\n    bool private redeemPaused = false;\n    bool private recollateralizePaused = false;\n    bool private buyBackPaused = false;\n    bool private collateralPricePaused = false;\n\n    /* ========== MODIFIERS ========== */\n\n    modifier onlyByOwnerOrGovernance() {\n        require(msg.sender == timelock_address || msg.sender == owner_address, \"You are not the owner or the governance timelock\");\n        _;\n    }\n\n    modifier notRedeemPaused() {\n        require(redeemPaused == false, \"Redeeming is paused\");\n        _;\n    }\n\n    modifier notMintPaused() {\n        require(mintPaused == false, \"Minting is paused\");\n        _;\n    }\n \n    /* ========== CONSTRUCTOR ========== */\n    \n    constructor(\n        address _frax_contract_address,\n        address _fxs_contract_address,\n        address _collateral_address,\n        address _creator_address,\n        address _timelock_address,\n        uint256 _pool_ceiling\n    ) public {\n        FRAX = FRAXStablecoin(_frax_contract_address);\n        FXS = FRAXShares(_fxs_contract_address);\n        frax_contract_address = _frax_contract_address;\n        fxs_contract_address = _fxs_contract_address;\n        collateral_address = _collateral_address;\n        timelock_address = _timelock_address;\n        owner_address = _creator_address;\n        collateral_token = ERC20(_collateral_address);\n        pool_ceiling = _pool_ceiling;\n        missing_decimals = uint(18).sub(collateral_token.decimals());\n\n        _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n        grantRole(MINT_PAUSER, timelock_address);\n        grantRole(REDEEM_PAUSER, timelock_address);\n        grantRole(RECOLLATERALIZE_PAUSER, timelock_address);\n        grantRole(BUYBACK_PAUSER, timelock_address);\n        grantRole(COLLATERAL_PRICE_PAUSER, timelock_address);\n    }\n\n    /* ========== VIEWS ========== */\n\n    // Returns dollar value of collateral held in this Frax pool\n    function collatDollarBalance() public view returns (uint256) {\n        uint256 eth_usd_price = FRAX.eth_usd_price();\n        uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals)));\n\n        uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price);\n        return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6);    \n    }\n\n    // Returns the value of excess collateral held in this Frax pool, compared to what is needed to maintain the global collateral ratio\n    function availableExcessCollatDV() public view returns (uint256) {\n        uint256 total_supply = FRAX.totalSupply();\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n        uint256 global_collat_value = FRAX.globalCollateralValue();\n\n        if (global_collateral_ratio \u003e COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR \u003e 1\n        uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio\n        if (global_collat_value \u003e required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18);\n        else return 0;\n    }\n\n    /* ========== PUBLIC FUNCTIONS ========== */\n    \n    // Returns the price of the pool collateral in USD\n    function getCollateralPrice() public view returns (uint256) {\n        if(collateralPricePaused == true){\n            return pausedPrice;\n        } else {\n            uint256 eth_usd_price = FRAX.eth_usd_price();\n            return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals)));\n        }\n    }\n\n    function setCollatETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyByOwnerOrGovernance {\n        collat_eth_oracle_address = _collateral_weth_oracle_address;\n        collatEthOracle = UniswapPairOracle(_collateral_weth_oracle_address);\n        weth_address = _weth_address;\n    }\n\n    // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency \n    function mint1t1FRAX(uint256 collateral_amount, uint256 FRAX_out_min) external notMintPaused {\n        uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n\n        require(global_collateral_ratio \u003e= COLLATERAL_RATIO_MAX, \"Collateral ratio must be \u003e= 1\");\n        require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) \u003c= pool_ceiling, \"[Pool\u0027s Closed]: Ceiling reached\");\n        \n        (uint256 frax_amount_d18) = FraxPoolLibrary.calcMint1t1FRAX(\n            getCollateralPrice(),\n            minting_fee,\n            collateral_amount_d18\n        ); //1 FRAX for each $1 worth of collateral\n\n        require(FRAX_out_min \u003c= frax_amount_d18, \"Slippage limit reached\");\n        collateral_token.transferFrom(msg.sender, address(this), collateral_amount);\n        FRAX.pool_mint(msg.sender, frax_amount_d18);\n    }\n\n    // 0% collateral-backed\n    function mintAlgorithmicFRAX(uint256 fxs_amount_d18, uint256 FRAX_out_min) external notMintPaused {\n        uint256 fxs_price = FRAX.fxs_price();\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n        require(global_collateral_ratio == 0, \"Collateral ratio must be 0\");\n        \n        (uint256 frax_amount_d18) = FraxPoolLibrary.calcMintAlgorithmicFRAX(\n            minting_fee, \n            fxs_price, // X FXS / 1 USD\n            fxs_amount_d18\n        );\n\n        require(FRAX_out_min \u003c= frax_amount_d18, \"Slippage limit reached\");\n        FXS.pool_burn_from(msg.sender, fxs_amount_d18);\n        FRAX.pool_mint(msg.sender, frax_amount_d18);\n    }\n\n    // Will fail if fully collateralized or fully algorithmic\n    // \u003e 0% and \u003c 100% collateral-backed\n    function mintFractionalFRAX(uint256 collateral_amount, uint256 fxs_amount, uint256 FRAX_out_min) external notMintPaused {\n        uint256 frax_price = FRAX.frax_price();\n        uint256 fxs_price = FRAX.fxs_price();\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n\n        require(global_collateral_ratio \u003c COLLATERAL_RATIO_MAX \u0026\u0026 global_collateral_ratio \u003e 0, \"Collateral ratio needs to be between .000001 and .999999\");\n        require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) \u003c= pool_ceiling, \"Pool ceiling reached, no more FRAX can be minted with this collateral\");\n\n        uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);\n        FraxPoolLibrary.MintFF_Params memory input_params = FraxPoolLibrary.MintFF_Params(\n            minting_fee, \n            fxs_price,\n            frax_price,\n            getCollateralPrice(),\n            fxs_amount,\n            collateral_amount_d18,\n            (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)),\n            pool_ceiling,\n            global_collateral_ratio\n        );\n\n        (uint256 mint_amount, uint256 fxs_needed) = FraxPoolLibrary.calcMintFractionalFRAX(input_params);\n\n        require(FRAX_out_min \u003c= mint_amount, \"Slippage limit reached\");\n        require(fxs_needed \u003c= fxs_amount, \"Not enough FXS inputted\");\n        FXS.pool_burn_from(msg.sender, fxs_needed);\n        collateral_token.transferFrom(msg.sender, address(this), collateral_amount);\n        FRAX.pool_mint(msg.sender, mint_amount);\n    }\n\n    // Redeem collateral. 100% collateral-backed\n    function redeem1t1FRAX(uint256 FRAX_amount, uint256 COLLATERAL_out_min) external notRedeemPaused {\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n        require(global_collateral_ratio == COLLATERAL_RATIO_MAX, \"Collateral ratio must be == 1\");\n\n        // Need to adjust for decimals of collateral\n        uint256 FRAX_amount_precision = FRAX_amount.div(10 ** missing_decimals);\n        (uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX(\n            getCollateralPrice(),\n            FRAX_amount_precision,\n            redemption_fee\n        );\n\n        require(collateral_needed \u003c= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), \"Not enough collateral in pool\");\n\n        redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed);\n        unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed);\n        lastRedeemed[msg.sender] = block.number;\n\n        require(COLLATERAL_out_min \u003c= collateral_needed, \"Slippage limit reached\");\n        \n        // Move all external functions to the end\n        FRAX.pool_burn_from(msg.sender, FRAX_amount);\n    }\n\n    // Will fail if fully collateralized or algorithmic\n    // Redeem FRAX for collateral and FXS. \u003e 0% and \u003c 100% collateral-backed\n    function redeemFractionalFRAX(uint256 FRAX_amount, uint256 FXS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused {\n        uint256 fxs_price = FRAX.fxs_price();\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n\n        require(global_collateral_ratio \u003c COLLATERAL_RATIO_MAX \u0026\u0026 global_collateral_ratio \u003e 0, \"Collateral ratio needs to be between .000001 and .999999\");\n        uint256 col_price_usd = getCollateralPrice();\n\n        uint256 FRAX_amount_post_fee = FRAX_amount.sub((FRAX_amount.mul(redemption_fee)).div(PRICE_PRECISION));\n        uint256 fxs_dollar_value_d18 = FRAX_amount_post_fee.sub(FRAX_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION));\n        uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price);\n\n        // Need to adjust for decimals of collateral\n        uint256 FRAX_amount_precision = FRAX_amount_post_fee.div(10 ** missing_decimals);\n        uint256 collateral_dollar_value = FRAX_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION);\n        uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd);\n\n        redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount);\n        unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount);\n\n        redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount);\n        unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount);\n\n        lastRedeemed[msg.sender] = block.number;\n\n        require(collateral_amount \u003c= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), \"Not enough collateral in pool\");\n        require(COLLATERAL_out_min \u003c= collateral_amount, \"Slippage limit reached [collateral]\");\n        require(FXS_out_min \u003c= fxs_amount, \"Slippage limit reached [FXS]\");\n        \n        // Move all external functions to the end\n        FRAX.pool_burn_from(msg.sender, FRAX_amount);\n        FXS.pool_mint(address(this), fxs_amount);\n    }\n\n    // Redeem FRAX for FXS. 0% collateral-backed\n    function redeemAlgorithmicFRAX(uint256 FRAX_amount, uint256 FXS_out_min) external notRedeemPaused {\n        uint256 fxs_price = FRAX.fxs_price();\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n\n        require(global_collateral_ratio == 0, \"Collateral ratio must be 0\"); \n        uint256 fxs_dollar_value_d18 = FRAX_amount;\n        fxs_dollar_value_d18 = fxs_dollar_value_d18.sub((fxs_dollar_value_d18.mul(redemption_fee)).div(PRICE_PRECISION)); //apply redemption fee\n\n        uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price);\n        \n        redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount);\n        unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount);\n        \n        lastRedeemed[msg.sender] = block.number;\n        \n        require(FXS_out_min \u003c= fxs_amount, \"Slippage limit reached\");\n        // Move all external functions to the end\n        FRAX.pool_burn_from(msg.sender, FRAX_amount);\n        FXS.pool_mint(address(this), fxs_amount);\n    }\n\n    // After a redemption happens, transfer the newly minted FXS and owed collateral from this pool\n    // contract to the user. Redemption is split into two functions to prevent flash loans from being able\n    // to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system.\n    function collectRedemption() external {\n        require((lastRedeemed[msg.sender].add(redemption_delay)) \u003c= block.number, \"Must wait for redemption_delay blocks before collecting redemption\");\n        bool sendFXS = false;\n        bool sendCollateral = false;\n        uint FXSAmount;\n        uint CollateralAmount;\n\n        // Use Checks-Effects-Interactions pattern\n        if(redeemFXSBalances[msg.sender] \u003e 0){\n            FXSAmount = redeemFXSBalances[msg.sender];\n            redeemFXSBalances[msg.sender] = 0;\n            unclaimedPoolFXS = unclaimedPoolFXS.sub(FXSAmount);\n\n            sendFXS = true;\n        }\n        \n        if(redeemCollateralBalances[msg.sender] \u003e 0){\n            CollateralAmount = redeemCollateralBalances[msg.sender];\n            redeemCollateralBalances[msg.sender] = 0;\n            unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount);\n\n            sendCollateral = true;\n        }\n\n        if(sendFXS == true){\n            FXS.transfer(msg.sender, FXSAmount);\n        }\n        if(sendCollateral == true){\n            collateral_token.transfer(msg.sender, CollateralAmount);\n        }\n    }\n\n\n    // When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target\n    // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral\n    // This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate\n    // Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity\n    function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external {\n        require(recollateralizePaused == false, \"Recollateralize is paused\");\n        uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);\n        uint256 fxs_price = FRAX.fxs_price();\n        uint256 frax_total_supply = FRAX.totalSupply();\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n        uint256 global_collat_value = FRAX.globalCollateralValue();\n        \n        (uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner(\n            collateral_amount_d18,\n            getCollateralPrice(),\n            global_collat_value,\n            frax_total_supply,\n            global_collateral_ratio\n        ); \n\n        uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals);\n\n        uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate)).div(fxs_price);\n\n        require(FXS_out_min \u003c= fxs_paid_back, \"Slippage limit reached\");\n        collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision);\n        FXS.pool_mint(msg.sender, fxs_paid_back);\n        \n    }\n\n    // Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool\n    // This can also happen if the collateral ratio \u003e 1\n    function buyBackFXS(uint256 FXS_amount, uint256 COLLATERAL_out_min) external {\n        require(buyBackPaused == false, \"Buyback is paused\");\n        uint256 fxs_price = FRAX.fxs_price();\n        \n        FraxPoolLibrary.BuybackFXS_Params memory input_params = FraxPoolLibrary.BuybackFXS_Params(\n            availableExcessCollatDV(),\n            fxs_price,\n            getCollateralPrice(),\n            FXS_amount\n        );\n\n        (uint256 collateral_equivalent_d18) = FraxPoolLibrary.calcBuyBackFXS(input_params);\n        uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals);\n\n        require(COLLATERAL_out_min \u003c= collateral_precision, \"Slippage limit reached\");\n        // Give the sender their desired collateral and burn the FXS\n        FXS.pool_burn_from(msg.sender, FXS_amount);\n        collateral_token.transfer(msg.sender, collateral_precision);\n    }\n\n    /* ========== RESTRICTED FUNCTIONS ========== */\n\n    function toggleMinting() external {\n        require(hasRole(MINT_PAUSER, msg.sender));\n        mintPaused = !mintPaused;\n    }\n    \n    function toggleRedeeming() external {\n        require(hasRole(REDEEM_PAUSER, msg.sender));\n        redeemPaused = !redeemPaused;\n    }\n\n    function toggleRecollateralize() external {\n        require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender));\n        recollateralizePaused = !recollateralizePaused;\n    }\n    \n    function toggleBuyBack() external {\n        require(hasRole(BUYBACK_PAUSER, msg.sender));\n        buyBackPaused = !buyBackPaused;\n    }\n\n    function toggleCollateralPrice() external {\n        require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender));\n        // If pausing, set paused price; else if unpausing, clear pausedPrice\n        if(collateralPricePaused == false){\n            pausedPrice = getCollateralPrice();\n        } else {\n            pausedPrice = 0;\n        }\n        collateralPricePaused = !collateralPricePaused;\n    }\n\n    // Combined into one function due to 24KiB contract memory limit\n    function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay) external onlyByOwnerOrGovernance {\n        pool_ceiling = new_ceiling;\n        bonus_rate = new_bonus_rate;\n        redemption_delay = new_redemption_delay;\n        minting_fee = FRAX.minting_fee();\n        redemption_fee = FRAX.redemption_fee();\n    }\n\n    function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {\n        timelock_address = new_timelock;\n    }\n\n    function setOwner(address _owner_address) external onlyByOwnerOrGovernance {\n        owner_address = _owner_address;\n    }\n\n    /* ========== EVENTS ========== */\n\n}"},"FraxPoolLibrary.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.6.0;\npragma experimental ABIEncoderV2;\n\nimport \"./SafeMath.sol\";\n\n\n\nlibrary FraxPoolLibrary {\n    using SafeMath for uint256;\n\n    // Constants for various precisions\n    uint256 private constant PRICE_PRECISION = 1e6;\n\n    // ================ Structs ================\n    // Needed to lower stack size\n    struct MintFF_Params {\n        uint256 mint_fee; \n        uint256 fxs_price_usd; \n        uint256 frax_price_usd; \n        uint256 col_price_usd;\n        uint256 fxs_amount;\n        uint256 collateral_amount;\n        uint256 collateral_token_balance;\n        uint256 pool_ceiling;\n        uint256 col_ratio;\n    }\n\n    struct BuybackFXS_Params {\n        uint256 excess_collateral_dollar_value_d18;\n        uint256 fxs_price_usd;\n        uint256 col_price_usd;\n        uint256 FXS_amount;\n    }\n\n    // ================ Functions ================\n\n    function calcMint1t1FRAX(uint256 col_price, uint256 mint_fee, uint256 collateral_amount_d18) public pure returns (uint256) {\n        uint256 col_price_usd = col_price;\n        uint256 c_dollar_value_d18 = (collateral_amount_d18.mul(col_price_usd)).div(1e6);\n        return c_dollar_value_d18.sub((c_dollar_value_d18.mul(mint_fee)).div(1e6));\n    }\n\n    function calcMintAlgorithmicFRAX(uint256 mint_fee, uint256 fxs_price_usd, uint256 fxs_amount_d18) public pure returns (uint256) {\n        uint256 fxs_dollar_value_d18 = fxs_amount_d18.mul(fxs_price_usd).div(1e6);\n        return fxs_dollar_value_d18.sub((fxs_dollar_value_d18.mul(mint_fee)).div(1e6));\n    }\n\n    // Must be internal because of the struct\n    function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) {\n        // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error\n        // The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount \n        uint256 fxs_dollar_value_d18;\n        uint256 c_dollar_value_d18;\n        \n        // Scoping for stack concerns\n        {    \n            // USD amounts of the collateral and the FXS\n            fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6);\n            c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6);\n\n        }\n        uint calculated_fxs_dollar_value_d18 = \n                    (c_dollar_value_d18.mul(1e6).div(params.col_ratio))\n                    .sub(c_dollar_value_d18);\n\n        uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd);\n\n        return (\n            (c_dollar_value_d18.add(calculated_fxs_dollar_value_d18)).sub(((c_dollar_value_d18.add(calculated_fxs_dollar_value_d18)).mul(params.mint_fee)).div(1e6)),\n            calculated_fxs_needed\n        );\n    }\n\n    function calcRedeem1t1FRAX(uint256 col_price_usd, uint256 FRAX_amount, uint256 redemption_fee) public pure returns (uint256) {\n        uint256 collateral_needed_d18 = FRAX_amount.mul(1e6).div(col_price_usd);\n        return collateral_needed_d18.sub((collateral_needed_d18.mul(redemption_fee)).div(1e6));\n    }\n\n    // Must be internal because of the struct\n    function calcBuyBackFXS(BuybackFXS_Params memory params) internal pure returns (uint256) {\n        // If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral\n        require(params.excess_collateral_dollar_value_d18 \u003e 0, \"No excess collateral to buy back!\");\n\n        // Make sure not to take more than is available\n        uint256 fxs_dollar_value_d18 = params.FXS_amount.mul(params.fxs_price_usd).div(1e6);\n        require(fxs_dollar_value_d18 \u003c= params.excess_collateral_dollar_value_d18, \"You are trying to buy back more than the excess!\");\n\n        // Get the equivalent amount of collateral based on the market value of FXS provided \n        uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd);\n        //collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6));\n\n        return (\n            collateral_equivalent_d18\n        );\n\n    }\n\n\n    // Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization)\n    function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) {\n        uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6\n        // Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize\n        uint256 recollateralization_left = target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow\n        return(recollateralization_left);\n    }\n\n    function calcRecollateralizeFRAXInner(\n        uint256 collateral_amount, \n        uint256 col_price,\n        uint256 global_collat_value,\n        uint256 frax_total_supply,\n        uint256 global_collateral_ratio\n    ) public pure returns (uint256, uint256) {\n        uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6);\n        uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6\n        uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6);\n\n        uint256 amount_to_recollat;\n        if(collat_value_attempted \u003c= recollat_possible){\n            amount_to_recollat = collat_value_attempted;\n        } else {\n            amount_to_recollat = recollat_possible;\n        }\n\n        return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat);\n\n    }\n\n}"},"FXS.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./Context.sol\";\nimport \"./ERC20Custom.sol\";\nimport \"./IERC20.sol\";\nimport \"./Frax.sol\";\nimport \"./SafeMath.sol\";\nimport \"./AccessControl.sol\";\n\ncontract FRAXShares is ERC20Custom, AccessControl {\n    using SafeMath for uint256;\n\n    /* ========== STATE VARIABLES ========== */\n\n    string public symbol;\n    string public name;\n    uint8 public constant decimals = 18;\n    address public FRAXStablecoinAdd;\n    \n    uint256 public constant genesis_supply = 100000000e18; // 100M is printed upon genesis\n    uint256 public FXS_DAO_min; // Minimum FXS required to join DAO groups \n\n    address public owner_address;\n    address public oracle_address;\n    address public timelock_address; // Governance timelock address\n    FRAXStablecoin private FRAX;\n\n    bool public trackingVotes = true; // Tracking votes (only change if need to disable votes)\n\n    // A checkpoint for marking number of votes from a given block\n    struct Checkpoint {\n        uint32 fromBlock;\n        uint96 votes;\n    }\n\n    // A record of votes checkpoints for each account, by index\n    mapping (address =\u003e mapping (uint32 =\u003e Checkpoint)) public checkpoints;\n\n    // The number of checkpoints for each account\n    mapping (address =\u003e uint32) public numCheckpoints;\n\n    /* ========== MODIFIERS ========== */\n\n    modifier onlyPools() {\n       require(FRAX.frax_pools(msg.sender) == true, \"Only frax pools can mint new FRAX\");\n        _;\n    } \n    \n    modifier onlyByOwnerOrGovernance() {\n        require(msg.sender == owner_address || msg.sender == timelock_address, \"You are not an owner or the governance timelock\");\n        _;\n    }\n\n    /* ========== CONSTRUCTOR ========== */\n\n    constructor(\n        string memory _name,\n        string memory _symbol, \n        address _oracle_address,\n        address _owner_address,\n        address _timelock_address\n    ) public {\n        name = _name;\n        symbol = _symbol;\n        owner_address = _owner_address;\n        oracle_address = _oracle_address;\n        timelock_address = _timelock_address;\n        _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n        _mint(owner_address, genesis_supply);\n\n        // Do a checkpoint for the owner\n        _writeCheckpoint(owner_address, 0, 0, uint96(genesis_supply));\n    }\n\n    /* ========== RESTRICTED FUNCTIONS ========== */\n\n    function setOracle(address new_oracle) external onlyByOwnerOrGovernance {\n        oracle_address = new_oracle;\n    }\n\n    function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {\n        timelock_address = new_timelock;\n    }\n    \n    function setFRAXAddress(address frax_contract_address) external onlyByOwnerOrGovernance {\n        FRAX = FRAXStablecoin(frax_contract_address);\n    }\n    \n    function setFXSMinDAO(uint256 min_FXS) external onlyByOwnerOrGovernance {\n        FXS_DAO_min = min_FXS;\n    }\n\n    function setOwner(address _owner_address) external onlyByOwnerOrGovernance {\n        owner_address = _owner_address;\n    }\n\n    function mint(address to, uint256 amount) public onlyPools {\n        _mint(to, amount);\n    }\n    \n    // This function is what other frax pools will call to mint new FXS (similar to the FRAX mint) \n    function pool_mint(address m_address, uint256 m_amount) external onlyPools {        \n        if(trackingVotes){\n            uint32 srcRepNum = numCheckpoints[address(this)];\n            uint96 srcRepOld = srcRepNum \u003e 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0;\n            uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), \"pool_mint new votes overflows\");\n            _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes\n            trackVotes(address(this), m_address, uint96(m_amount));\n        }\n\n        super._mint(m_address, m_amount);\n        emit FXSMinted(address(this), m_address, m_amount);\n    }\n\n    // This function is what other frax pools will call to burn FXS \n    function pool_burn_from(address b_address, uint256 b_amount) external onlyPools {\n        if(trackingVotes){\n            trackVotes(b_address, address(this), uint96(b_amount));\n            uint32 srcRepNum = numCheckpoints[address(this)];\n            uint96 srcRepOld = srcRepNum \u003e 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0;\n            uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), \"pool_burn_from new votes underflows\");\n            _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes\n        }\n\n        super._burnFrom(b_address, b_amount);\n        emit FXSBurned(b_address, address(this), b_amount);\n    }\n\n    function toggleVotes() external onlyByOwnerOrGovernance {\n        trackingVotes = !trackingVotes;\n    }\n\n    /* ========== OVERRIDDEN PUBLIC FUNCTIONS ========== */\n\n    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n        if(trackingVotes){\n            // Transfer votes\n            trackVotes(_msgSender(), recipient, uint96(amount));\n        }\n\n        _transfer(_msgSender(), recipient, amount);\n        return true;\n    }\n\n    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n        if(trackingVotes){\n            // Transfer votes\n            trackVotes(sender, recipient, uint96(amount));\n        }\n\n        _transfer(sender, recipient, amount);\n        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n\n        return true;\n    }\n\n    /* ========== PUBLIC FUNCTIONS ========== */\n\n    /**\n     * @notice Gets the current votes balance for `account`\n     * @param account The address to get votes balance\n     * @return The number of current votes for `account`\n     */\n    function getCurrentVotes(address account) external view returns (uint96) {\n        uint32 nCheckpoints = numCheckpoints[account];\n        return nCheckpoints \u003e 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;\n    }\n\n    /**\n     * @notice Determine the prior number of votes for an account as of a block number\n     * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.\n     * @param account The address of the account to check\n     * @param blockNumber The block number to get the vote balance at\n     * @return The number of votes the account had as of the given block\n     */\n    function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {\n        require(blockNumber \u003c block.number, \"FXS::getPriorVotes: not yet determined\");\n\n        uint32 nCheckpoints = numCheckpoints[account];\n        if (nCheckpoints == 0) {\n            return 0;\n        }\n\n        // First check most recent balance\n        if (checkpoints[account][nCheckpoints - 1].fromBlock \u003c= blockNumber) {\n            return checkpoints[account][nCheckpoints - 1].votes;\n        }\n\n        // Next check implicit zero balance\n        if (checkpoints[account][0].fromBlock \u003e blockNumber) {\n            return 0;\n        }\n\n        uint32 lower = 0;\n        uint32 upper = nCheckpoints - 1;\n        while (upper \u003e lower) {\n            uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow\n            Checkpoint memory cp = checkpoints[account][center];\n            if (cp.fromBlock == blockNumber) {\n                return cp.votes;\n            } else if (cp.fromBlock \u003c blockNumber) {\n                lower = center;\n            } else {\n                upper = center - 1;\n            }\n        }\n        return checkpoints[account][lower].votes;\n    }\n\n    /* ========== INTERNAL FUNCTIONS ========== */\n\n    // From compound\u0027s _moveDelegates\n    // Keep track of votes. \"Delegates\" is a misnomer here\n    function trackVotes(address srcRep, address dstRep, uint96 amount) internal {\n        if (srcRep != dstRep \u0026\u0026 amount \u003e 0) {\n            if (srcRep != address(0)) {\n                uint32 srcRepNum = numCheckpoints[srcRep];\n                uint96 srcRepOld = srcRepNum \u003e 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;\n                uint96 srcRepNew = sub96(srcRepOld, amount, \"FXS::_moveVotes: vote amount underflows\");\n                _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);\n            }\n\n            if (dstRep != address(0)) {\n                uint32 dstRepNum = numCheckpoints[dstRep];\n                uint96 dstRepOld = dstRepNum \u003e 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;\n                uint96 dstRepNew = add96(dstRepOld, amount, \"FXS::_moveVotes: vote amount overflows\");\n                _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);\n            }\n        }\n    }\n\n    function _writeCheckpoint(address voter, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {\n      uint32 blockNumber = safe32(block.number, \"FXS::_writeCheckpoint: block number exceeds 32 bits\");\n\n      if (nCheckpoints \u003e 0 \u0026\u0026 checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {\n          checkpoints[voter][nCheckpoints - 1].votes = newVotes;\n      } else {\n          checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);\n          numCheckpoints[voter] = nCheckpoints + 1;\n      }\n\n      emit VoterVotesChanged(voter, oldVotes, newVotes);\n    }\n\n    function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {\n        require(n \u003c 2**32, errorMessage);\n        return uint32(n);\n    }\n\n    function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {\n        require(n \u003c 2**96, errorMessage);\n        return uint96(n);\n    }\n\n    function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {\n        uint96 c = a + b;\n        require(c \u003e= a, errorMessage);\n        return c;\n    }\n\n    function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {\n        require(b \u003c= a, errorMessage);\n        return a - b;\n    }\n\n    function getChainId() internal pure returns (uint) {\n        uint256 chainId;\n        assembly { chainId := chainid() }\n        return chainId;\n    }\n\n    /* ========== EVENTS ========== */\n    \n    /// @notice An event thats emitted when a voters account\u0027s vote balance changes\n    event VoterVotesChanged(address indexed voter, uint previousBalance, uint newBalance);\n\n    // Track FXS burned\n    event FXSBurned(address indexed from, address indexed to, uint256 amount);\n\n    // Track FXS minted\n    event FXSMinted(address indexed from, address indexed to, uint256 amount);\n\n}\n"},"Governance.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./FXS.sol\";\n\n// From https://compound.finance/docs/governance\n// and https://github.com/compound-finance/compound-protocol/tree/master/contracts/Governance\ncontract GovernorAlpha {\n    /// @notice The name of this contract\n    string public constant name = \"FXS Governor Alpha\";\n\n    /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed\n    function quorumVotes() public pure returns (uint) { return 4000000e18; } // 4,000,000 = 4% of FXS\n\n    /// @notice The number of votes required in order for a voter to become a proposer\n    function proposalThreshold() public pure returns (uint) { return 1000000e18; } // 1,000,000 = 1% of FXS\n\n    /// @notice The maximum number of actions that can be included in a proposal\n    function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions\n\n    /// @notice The delay before voting on a proposal may take place, once proposed\n    // This also helps protect against flash loan attacks because only the vote balance at the proposal start block is considered\n    function votingDelay() public pure returns (uint) { return 1; } // 1 block\n\n    /// @notice The duration of voting on a proposal, in blocks\n    // function votingPeriod() public pure returns (uint) { return 17280; } // ~3 days in blocks (assuming 15s blocks)\n    uint public votingPeriod = 17280;\n    \n    /// @notice The address of the Timelock\n    TimelockInterface public timelock;\n\n    // The address of the FXS token\n    FRAXShares public fxs;\n\n    /// @notice The address of the Governor Guardian\n    address public guardian;\n\n    /// @notice The total number of proposals\n    uint public proposalCount = 0;\n\n    struct Proposal {\n        // @notice Unique id for looking up a proposal\n        uint id;\n\n        // @notice Creator of the proposal\n        address proposer;\n\n        // @notice The timestamp that the proposal will be available for execution, set once the vote succeeds\n        uint eta;\n\n        // @notice the ordered list of target addresses for calls to be made\n        address[] targets;\n\n        // @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made\n        uint[] values;\n\n        // @notice The ordered list of function signatures to be called\n        string[] signatures;\n\n        // @notice The ordered list of calldata to be passed to each call\n        bytes[] calldatas;\n\n        // @notice The block at which voting begins: holders must delegate their votes prior to this block\n        uint startBlock;\n\n        // @notice The block at which voting ends: votes must be cast prior to this block\n        uint endBlock;\n\n        // @notice Current number of votes in favor of this proposal\n        uint forVotes;\n\n        // @notice Current number of votes in opposition to this proposal\n        uint againstVotes;\n\n        // @notice Flag marking whether the proposal has been canceled\n        bool canceled;\n\n        // @notice Flag marking whether the proposal has been executed\n        bool executed;\n\n        // @notice Title of the proposal (human-readable)\n        string title;\n\n        // @notice Description of the proposall (human-readable)\n        string description;\n\n        // @notice Receipts of ballots for the entire set of voters\n        mapping (address =\u003e Receipt) receipts;\n    }\n\n    /// @notice Ballot receipt record for a voter\n    struct Receipt {\n        // @notice Whether or not a vote has been cast\n        bool hasVoted;\n\n        // @notice Whether or not the voter supports the proposal\n        bool support;\n\n        // @notice The number of votes the voter had, which were cast\n        uint96 votes;\n    }\n\n    /// @notice Possible states that a proposal may be in\n    enum ProposalState {\n        Pending,\n        Active,\n        Canceled,\n        Defeated,\n        Succeeded,\n        Queued,\n        Expired,\n        Executed\n    }\n\n    /// @notice The official record of all proposals ever proposed\n    mapping (uint =\u003e Proposal) public proposals;\n\n    /// @notice The latest proposal for each proposer\n    mapping (address =\u003e uint) public latestProposalIds;\n\n    /// @notice The EIP-712 typehash for the contract\u0027s domain\n    bytes32 public constant DOMAIN_TYPEHASH = keccak256(\"EIP712Domain(string name,uint256 chainId,address verifyingContract)\");\n\n    /// @notice The EIP-712 typehash for the ballot struct used by the contract\n    bytes32 public constant BALLOT_TYPEHASH = keccak256(\"Ballot(uint256 proposalId,bool support)\");\n\n    /// @notice An event emitted when a new proposal is created\n    event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);\n\n    /// @notice An event emitted when a vote has been cast on a proposal\n    event VoteCast(address voter, uint proposalId, bool support, uint votes);\n\n    /// @notice An event emitted when a proposal has been canceled\n    event ProposalCanceled(uint id);\n\n    /// @notice An event emitted when a proposal has been queued in the Timelock\n    event ProposalQueued(uint id, uint eta);\n\n    /// @notice An event emitted when a proposal has been executed in the Timelock\n    event ProposalExecuted(uint id);\n\n    constructor(address timelock_, address fxs_, address guardian_) public {\n        timelock = TimelockInterface(timelock_);\n        fxs = FRAXShares(fxs_);\n        guardian = guardian_;\n    }\n\n    function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory title, string memory description) public returns (uint) {\n        require(fxs.getPriorVotes(msg.sender, sub256(block.number, 1)) \u003e= proposalThreshold(), \"GovernorAlpha::propose: proposer votes below proposal threshold\");\n        require(targets.length == values.length \u0026\u0026 targets.length == signatures.length \u0026\u0026 targets.length == calldatas.length, \"GovernorAlpha::propose: proposal function information arity mismatch\");\n        require(targets.length != 0, \"GovernorAlpha::propose: must provide actions\");\n        require(targets.length \u003c= proposalMaxOperations(), \"GovernorAlpha::propose: too many actions\");\n\n        uint latestProposalId = latestProposalIds[msg.sender];\n        if (latestProposalId != 0) {\n          ProposalState proposersLatestProposalState = state(latestProposalId);\n          require(proposersLatestProposalState != ProposalState.Active, \"GovernorAlpha::propose: one live proposal per proposer, found an already active proposal\");\n          require(proposersLatestProposalState != ProposalState.Pending, \"GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal\");\n        }\n\n        uint startBlock = add256(block.number, votingDelay());\n        uint endBlock = add256(startBlock, votingPeriod);\n\n        proposalCount++;\n        Proposal memory newProposal = Proposal({\n            id: proposalCount,\n            proposer: msg.sender,\n            eta: 0,\n            targets: targets,\n            values: values,\n            signatures: signatures,\n            calldatas: calldatas,\n            startBlock: startBlock,\n            endBlock: endBlock,\n            forVotes: 0,\n            againstVotes: 0,\n            canceled: false,\n            executed: false,\n            title: title,\n            description: description\n        });\n\n        proposals[newProposal.id] = newProposal;\n        latestProposalIds[newProposal.proposer] = newProposal.id;\n\n        emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);\n        return newProposal.id;\n    }\n\n    function queue(uint proposalId) public {\n        require(state(proposalId) == ProposalState.Succeeded, \"GovernorAlpha::queue: proposal can only be queued if it succeeded\");\n        Proposal storage proposal = proposals[proposalId];\n        uint eta = add256(block.timestamp, timelock.delay());\n        for (uint i = 0; i \u003c proposal.targets.length; i++) {\n            _queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);\n        }\n        proposal.eta = eta;\n        emit ProposalQueued(proposalId, eta);\n    }\n\n    function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal {\n        require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), \"GovernorAlpha::_queueOrRevert: proposal action already queued at eta\");\n        timelock.queueTransaction(target, value, signature, data, eta);\n    }\n\n    function execute(uint proposalId) public payable {\n        require(state(proposalId) == ProposalState.Queued, \"GovernorAlpha::execute: proposal can only be executed if it is queued\");\n        Proposal storage proposal = proposals[proposalId];\n        proposal.executed = true;\n        for (uint i = 0; i \u003c proposal.targets.length; i++) {\n            timelock.executeTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);\n        }\n        emit ProposalExecuted(proposalId);\n    }\n\n    function cancel(uint proposalId) public {\n        ProposalState state = state(proposalId);\n        require(state != ProposalState.Executed, \"GovernorAlpha::cancel: cannot cancel executed proposal\");\n\n        Proposal storage proposal = proposals[proposalId];\n        require(msg.sender == guardian || fxs.getPriorVotes(proposal.proposer, sub256(block.number, 1)) \u003c proposalThreshold(), \"GovernorAlpha::cancel: proposer at or above threshold\");\n\n        proposal.canceled = true;\n        for (uint i = 0; i \u003c proposal.targets.length; i++) {\n            timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);\n        }\n\n        emit ProposalCanceled(proposalId);\n    }\n\n    function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {\n        Proposal storage p = proposals[proposalId];\n        return (p.targets, p.values, p.signatures, p.calldatas);\n    }\n\n    function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) {\n        return proposals[proposalId].receipts[voter];\n    }\n\n    function state(uint proposalId) public view returns (ProposalState) {\n        require(proposalCount \u003e= proposalId \u0026\u0026 proposalId \u003e 0, \"GovernorAlpha::state: invalid proposal id\");\n        Proposal storage proposal = proposals[proposalId];\n        if (proposal.canceled) {\n            return ProposalState.Canceled;\n        } else if (block.number \u003c= proposal.startBlock) {\n            return ProposalState.Pending;\n        } else if (block.number \u003c= proposal.endBlock) {\n            return ProposalState.Active;\n        } else if (proposal.forVotes \u003c= proposal.againstVotes || proposal.forVotes \u003c quorumVotes()) {\n            return ProposalState.Defeated;\n        } else if (proposal.eta == 0) {\n            return ProposalState.Succeeded;\n        } else if (proposal.executed) {\n            return ProposalState.Executed;\n        } else if (block.timestamp \u003e= add256(proposal.eta, timelock.GRACE_PERIOD())) {\n            return ProposalState.Expired;\n        } else {\n            return ProposalState.Queued;\n        }\n    }\n\n    function castVote(uint proposalId, bool support) public {\n        return _castVote(msg.sender, proposalId, support);\n    }\n\n    function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public {\n        bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));\n        bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));\n        bytes32 digest = keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n        address signatory = ecrecover(digest, v, r, s);\n        require(signatory != address(0), \"GovernorAlpha::castVoteBySig: invalid signature\");\n        return _castVote(signatory, proposalId, support);\n    }\n\n    function _castVote(address voter, uint proposalId, bool support) internal {\n        require(state(proposalId) == ProposalState.Active, \"GovernorAlpha::_castVote: voting is closed\");\n        Proposal storage proposal = proposals[proposalId];\n        Receipt storage receipt = proposal.receipts[voter];\n        require(receipt.hasVoted == false, \"GovernorAlpha::_castVote: voter already voted\");\n        uint96 votes = fxs.getPriorVotes(voter, proposal.startBlock);\n\n        if (support) {\n            proposal.forVotes = add256(proposal.forVotes, votes);\n        } else {\n            proposal.againstVotes = add256(proposal.againstVotes, votes);\n        }\n\n        receipt.hasVoted = true;\n        receipt.support = support;\n        receipt.votes = votes;\n\n        emit VoteCast(voter, proposalId, support, votes);\n    }\n\n    function __acceptAdmin() public {\n        require(msg.sender == guardian, \"GovernorAlpha::__acceptAdmin: sender must be gov guardian\");\n        timelock.acceptAdmin();\n    }\n\n    function __abdicate() public {\n        require(msg.sender == guardian, \"GovernorAlpha::__abdicate: sender must be gov guardian\");\n        guardian = address(0);\n    }\n\n    function __setVotingPeriod(uint period) public {\n        require(msg.sender == guardian, \"GovernorAlpha::__setVotingPeriod: sender must be gov guardian\");\n        votingPeriod = period;\n    }\n\n    function __setTimelockAddress(address timelock_) public {\n        require(msg.sender == guardian, \"GovernorAlpha::__setTimelockAddress: sender must be gov guardian\");\n        timelock = TimelockInterface(timelock_);\n    }\n\n    function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {\n        require(msg.sender == guardian, \"GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian\");\n        timelock.queueTransaction(address(timelock), 0, \"setPendingAdmin(address)\", abi.encode(newPendingAdmin), eta);\n    }\n\n    function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {\n        require(msg.sender == guardian, \"GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian\");\n        timelock.executeTransaction(address(timelock), 0, \"setPendingAdmin(address)\", abi.encode(newPendingAdmin), eta);\n    }\n\n    function add256(uint256 a, uint256 b) internal pure returns (uint) {\n        uint c = a + b;\n        require(c \u003e= a, \"addition overflow\");\n        return c;\n    }\n\n    function sub256(uint256 a, uint256 b) internal pure returns (uint) {\n        require(b \u003c= a, \"subtraction underflow\");\n        return a - b;\n    }\n\n    function getChainId() internal pure returns (uint) {\n        uint chainId;\n        assembly { chainId := chainid() }\n        return chainId;\n    }\n}\n\ninterface TimelockInterface {\n    function delay() external view returns (uint);\n    function GRACE_PERIOD() external view returns (uint);\n    function acceptAdmin() external;\n    function queuedTransactions(bytes32 hash) external view returns (bool);\n    function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32);\n    function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external;\n    function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory);\n}\n"},"IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./Context.sol\";\nimport \"./SafeMath.sol\";\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP. Does not include\n * the optional functions; to access them see {ERC20Detailed}.\n */\ninterface IERC20 {\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller\u0027s account to `recipient`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address recipient, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller\u0027s tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender\u0027s allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `sender` to `recipient` using the\n     * allowance mechanism. `amount` is then deducted from the caller\u0027s\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n\n"},"IStakingRewards.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n\ninterface IStakingRewards {\n    // Views\n    function lastTimeRewardApplicable() external view returns (uint256);\n\n    function rewardPerToken() external view returns (uint256);\n\n    function earned(address account) external view returns (uint256);\n\n    function getRewardForDuration() external view returns (uint256);\n\n    function totalSupply() external view returns (uint256);\n\n    function balanceOf(address account) external view returns (uint256);\n\n    // Mutative\n\n    function stake(uint256 amount) external;\n\n    function withdraw(uint256 amount) external;\n\n    function getReward() external;\n\n    //function exit() external;\n}\n"},"IUniswapV2Callee.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ninterface IUniswapV2Callee {\n    function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;\n}\n"},"IUniswapV2ERC20.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ninterface IUniswapV2ERC20 {\n    event Approval(address indexed owner, address indexed spender, uint value);\n    event Transfer(address indexed from, address indexed to, uint value);\n\n    function name() external pure returns (string memory);\n    function symbol() external pure returns (string memory);\n    function decimals() external pure returns (uint8);\n    function totalSupply() external view returns (uint);\n    function balanceOf(address owner) external view returns (uint);\n    function allowance(address owner, address spender) external view returns (uint);\n\n    function approve(address spender, uint value) external returns (bool);\n    function transfer(address to, uint value) external returns (bool);\n    function transferFrom(address from, address to, uint value) external returns (bool);\n\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n    function PERMIT_TYPEHASH() external pure returns (bytes32);\n    function nonces(address owner) external view returns (uint);\n\n    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;\n}\n"},"IUniswapV2Factory.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ninterface IUniswapV2Factory {\n    event PairCreated(address indexed token0, address indexed token1, address pair, uint);\n\n    function feeTo() external view returns (address);\n    function feeToSetter() external view returns (address);\n\n    function getPair(address tokenA, address tokenB) external view returns (address pair);\n    function allPairs(uint) external view returns (address pair);\n    function allPairsLength() external view returns (uint);\n\n    function createPair(address tokenA, address tokenB) external returns (address pair);\n\n    function setFeeTo(address) external;\n    function setFeeToSetter(address) external;\n}\n"},"IUniswapV2Pair.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ninterface IUniswapV2Pair {\n    event Approval(address indexed owner, address indexed spender, uint value);\n    event Transfer(address indexed from, address indexed to, uint value);\n\n    function name() external pure returns (string memory);\n    function symbol() external pure returns (string memory);\n    function decimals() external pure returns (uint8);\n    function totalSupply() external view returns (uint);\n    function balanceOf(address owner) external view returns (uint);\n    function allowance(address owner, address spender) external view returns (uint);\n\n    function approve(address spender, uint value) external returns (bool);\n    function transfer(address to, uint value) external returns (bool);\n    function transferFrom(address from, address to, uint value) external returns (bool);\n\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n    function PERMIT_TYPEHASH() external pure returns (bytes32);\n    function nonces(address owner) external view returns (uint);\n\n    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;\n\n    event Mint(address indexed sender, uint amount0, uint amount1);\n    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);\n    event Swap(\n        address indexed sender,\n        uint amount0In,\n        uint amount1In,\n        uint amount0Out,\n        uint amount1Out,\n        address indexed to\n    );\n    event Sync(uint112 reserve0, uint112 reserve1);\n\n    function MINIMUM_LIQUIDITY() external pure returns (uint);\n    function factory() external view returns (address);\n    function token0() external view returns (address);\n    function token1() external view returns (address);\n    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);\n    function price0CumulativeLast() external view returns (uint);\n    function price1CumulativeLast() external view returns (uint);\n    function kLast() external view returns (uint);\n\n    function mint(address to) external returns (uint liquidity);\n    function burn(address to) external returns (uint amount0, uint amount1);\n    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;\n    function skim(address to) external;\n    function sync() external;\n\n    function initialize(address, address) external;\n\n\n\n\n\n\n\n\n\n\n\n\n    \n}\n"},"IUniswapV2Router01.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ninterface IUniswapV2Router01 {\n    function factory() external pure returns (address);\n    function WETH() external pure returns (address);\n\n    function addLiquidity(\n        address tokenA,\n        address tokenB,\n        uint amountADesired,\n        uint amountBDesired,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountA, uint amountB, uint liquidity);\n    function addLiquidityETH(\n        address token,\n        uint amountTokenDesired,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);\n    function removeLiquidity(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountA, uint amountB);\n    function removeLiquidityETH(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountToken, uint amountETH);\n    function removeLiquidityWithPermit(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountA, uint amountB);\n    function removeLiquidityETHWithPermit(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountToken, uint amountETH);\n    function swapExactTokensForTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external returns (uint[] memory amounts);\n    function swapTokensForExactTokens(\n        uint amountOut,\n        uint amountInMax,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external returns (uint[] memory amounts);\n    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        payable\n        returns (uint[] memory amounts);\n    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)\n        external\n        returns (uint[] memory amounts);\n    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        returns (uint[] memory amounts);\n    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n        external\n        payable\n        returns (uint[] memory amounts);\n\n    function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);\n    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);\n    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);\n    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);\n    function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);\n}"},"IUniswapV2Router02.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Router01.sol\u0027;\n\ninterface IUniswapV2Router02 is IUniswapV2Router01 {\n    function removeLiquidityETHSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountETH);\n    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountETH);\n\n    function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external;\n    function swapExactETHForTokensSupportingFeeOnTransferTokens(\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external payable;\n    function swapExactTokensForETHSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external;\n}"},"IWETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ninterface IWETH {\n    function deposit() external payable;\n    function transfer(address to, uint value) external returns (bool);\n    function transferFrom(address src, address dst, uint wad) external returns (bool);\n    function withdraw(uint) external;\n}"},"Math.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a \u003e= b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a \u003c b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow, so we distribute\n        return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);\n    }\n\n    // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)\n    function sqrt(uint y) internal pure returns (uint z) {\n        if (y \u003e 3) {\n            z = y;\n            uint x = y / 2 + 1;\n            while (x \u003c z) {\n                z = x;\n                x = (y / x + x) / 2;\n            }\n        } else if (y != 0) {\n            z = 1;\n        }\n    }\n}"},"MigrationHelper.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ncontract MigrationHelper {\n  address public owner;\n  uint256 public gov_to_timelock_eta;\n\n  modifier restricted() {\n    if (msg.sender == owner) _;\n  }\n\n  constructor(address _owner) public {\n    owner = _owner;\n  }\n\n  function setGovToTimeLockETA(uint256 _eta) public restricted {\n    gov_to_timelock_eta = _eta;\n  }\n}\n"},"Migrations.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ncontract Migrations {\n  address public owner;\n  uint public last_completed_migration;\n\n  modifier restricted() {\n    if (msg.sender == owner) _;\n  }\n\n  constructor() public {\n    owner = msg.sender;\n  }\n\n  function setCompleted(uint completed) public restricted {\n    last_completed_migration = completed;\n  }\n}\n"},"Owned.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n// https://docs.synthetix.io/contracts/Owned\ncontract Owned {\n    address public owner;\n    address public nominatedOwner;\n\n    constructor(address _owner) public {\n        require(_owner != address(0), \"Owner address cannot be 0\");\n        owner = _owner;\n        emit OwnerChanged(address(0), _owner);\n    }\n\n    function nominateNewOwner(address _owner) external onlyOwner {\n        nominatedOwner = _owner;\n        emit OwnerNominated(_owner);\n    }\n\n    function acceptOwnership() external {\n        require(msg.sender == nominatedOwner, \"You must be nominated before you can accept ownership\");\n        emit OwnerChanged(owner, nominatedOwner);\n        owner = nominatedOwner;\n        nominatedOwner = address(0);\n    }\n\n    modifier onlyOwner {\n        require(msg.sender == owner, \"Only the contract owner may perform this action\");\n        _;\n    }\n\n    event OwnerNominated(address newOwner);\n    event OwnerChanged(address oldOwner, address newOwner);\n}"},"Pausable.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n// Inheritance\nimport \"./Owned.sol\";\n\n// https://docs.synthetix.io/contracts/Pausable\nabstract contract Pausable is Owned {\n    uint public lastPauseTime;\n    bool public paused;\n\n    constructor() internal {\n        // This contract is abstract, and thus cannot be instantiated directly\n        require(owner != address(0), \"Owner must be set\");\n        // Paused will be false, and lastPauseTime will be 0 upon initialisation\n    }\n\n    /**\n     * @notice Change the paused state of the contract\n     * @dev Only the contract owner may call this.\n     */\n    function setPaused(bool _paused) external onlyOwner {\n        // Ensure we\u0027re actually changing the state before we do anything\n        if (_paused == paused) {\n            return;\n        }\n\n        // Set our paused state.\n        paused = _paused;\n\n        // If applicable, set the last pause time.\n        if (paused) {\n            lastPauseTime = now;\n        }\n\n        // Let everyone know that our pause state has changed.\n        emit PauseChanged(paused);\n    }\n\n    event PauseChanged(bool isPaused);\n\n    modifier notPaused {\n        require(!paused, \"This action cannot be performed while the contract is paused\");\n        _;\n    }\n}"},"Pool_USDC.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./FraxPool.sol\";\n\ncontract Pool_USDC is FraxPool {\n    address public USDC_address;\n    constructor(\n        address _frax_contract_address,\n        address _fxs_contract_address,\n        address _collateral_address,\n        address _creator_address,\n        address _timelock_address,\n        uint256 _pool_ceiling\n    ) \n    FraxPool(_frax_contract_address, _fxs_contract_address, _collateral_address, _creator_address, _timelock_address, _pool_ceiling)\n    public {\n        _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n        USDC_address = _collateral_address;\n    }\n}\n"},"Pool_USDT.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./FraxPool.sol\";\n\ncontract Pool_USDT is FraxPool {\n    address public USDT_address;\n    constructor(\n        address _frax_contract_address,\n        address _fxs_contract_address,\n        address _collateral_address,\n        address _creator_address,\n        address _timelock_address,\n        uint256 _pool_ceiling\n    ) \n    FraxPool(_frax_contract_address, _fxs_contract_address, _collateral_address, _creator_address, _timelock_address, _pool_ceiling)\n    public {\n        _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n        USDT_address = _collateral_address;\n    }\n}\n"},"ReentrancyGuard.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\ncontract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot\u0027s contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler\u0027s defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction\u0027s gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor () internal {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and make it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        // On the first call to nonReentrant, _notEntered will be true\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n\n        _;\n\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n}"},"RewardsDistributionRecipient.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n// Inheritance\nimport \"./Owned.sol\";\n\n\n// https://docs.synthetix.io/contracts/RewardsDistributionRecipient\nabstract contract RewardsDistributionRecipient is Owned {\n    address public rewardsDistribution;\n\n    //function notifyRewardAmount(uint256 reward) external virtual;\n\n    modifier onlyRewardsDistribution() {\n        require(msg.sender == rewardsDistribution, \"Caller is not RewardsDistribution contract\");\n        _;\n    }\n\n    function setRewardsDistribution(address _rewardsDistribution) external onlyOwner {\n        rewardsDistribution = _rewardsDistribution;\n    }\n}\n"},"SafeERC20.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./IERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using SafeMath for uint256;\n    using Address for address;\n\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(IERC20 token, address spender, uint256 value) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // \u0027safeIncreaseAllowance\u0027 and \u0027safeDecreaseAllowance\u0027\n        // solhint-disable-next-line max-line-length\n        require((value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 newAllowance = token.allowance(address(this), spender).add(value);\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity\u0027s return data size checking mechanism, since\n        // we\u0027re implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        if (returndata.length \u003e 0) { // Return data is optional\n            // solhint-disable-next-line max-line-length\n            require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n        }\n    }\n}"},"SafeMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n/**\n * @dev Wrappers over Solidity\u0027s arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it\u0027s recommended to use it always.\n */\nlibrary SafeMath {\n    /**\n     * @dev Returns the addition of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity\u0027s `+` operator.\n     *\n     * Requirements:\n     * - Addition cannot overflow.\n     */\n    function add(uint256 a, uint256 b) internal pure returns (uint256) {\n        uint256 c = a + b;\n        require(c \u003e= a, \"SafeMath: addition overflow\");\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting on\n     * overflow (when the result is negative).\n     *\n     * Counterpart to Solidity\u0027s `-` operator.\n     *\n     * Requirements:\n     * - Subtraction cannot overflow.\n     */\n    function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n        return sub(a, b, \"SafeMath: subtraction overflow\");\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n     * overflow (when the result is negative).\n     *\n     * Counterpart to Solidity\u0027s `-` operator.\n     *\n     * Requirements:\n     * - Subtraction cannot overflow.\n     *\n     * _Available since v2.4.0._\n     */\n    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b \u003c= a, errorMessage);\n        uint256 c = a - b;\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity\u0027s `*` operator.\n     *\n     * Requirements:\n     * - Multiplication cannot overflow.\n     */\n    function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n        // Gas optimization: this is cheaper than requiring \u0027a\u0027 not being zero, but the\n        // benefit is lost if \u0027b\u0027 is also tested.\n        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n        if (a == 0) {\n            return 0;\n        }\n\n        uint256 c = a * b;\n        require(c / a == b, \"SafeMath: multiplication overflow\");\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers. Reverts on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity\u0027s `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     */\n    function div(uint256 a, uint256 b) internal pure returns (uint256) {\n        return div(a, b, \"SafeMath: division by zero\");\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity\u0027s `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     *\n     * _Available since v2.4.0._\n     */\n    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        // Solidity only automatically asserts when dividing by 0\n        require(b \u003e 0, errorMessage);\n        uint256 c = a / b;\n        // assert(a == b * c + a % b); // There is no case in which this doesn\u0027t hold\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * Reverts when dividing by zero.\n     *\n     * Counterpart to Solidity\u0027s `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     */\n    function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n        return mod(a, b, \"SafeMath: modulo by zero\");\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * Reverts with custom message when dividing by zero.\n     *\n     * Counterpart to Solidity\u0027s `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     *\n     * _Available since v2.4.0._\n     */\n    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b != 0, errorMessage);\n        return a % b;\n    }\n}"},"Stake_FRAX_FXS.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./StakingRewards.sol\";\n\ncontract Stake_FRAX_FXS is StakingRewards {\n    constructor(\n        address _owner,\n        address _rewardsDistribution,\n        address _rewardsToken,\n        address _stakingToken,\n        address _frax_address,\n        address _timelock_address,\n        uint256 _pool_weight\n    ) \n    StakingRewards(_owner, _rewardsDistribution, _rewardsToken, _stakingToken, _frax_address, _timelock_address, _pool_weight)\n    public {}\n}"},"Stake_FRAX_USDC.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./StakingRewards.sol\";\n\ncontract Stake_FRAX_USDC is StakingRewards {\n    constructor(\n        address _owner,\n        address _rewardsDistribution,\n        address _rewardsToken,\n        address _stakingToken,\n        address _frax_address,\n        address _timelock_address,\n        uint256 _pool_weight\n    ) \n    StakingRewards(_owner, _rewardsDistribution, _rewardsToken, _stakingToken, _frax_address, _timelock_address, _pool_weight)\n    public {}\n}"},"Stake_FRAX_WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./StakingRewards.sol\";\n\ncontract Stake_FRAX_WETH is StakingRewards {\n    constructor(\n        address _owner,\n        address _rewardsDistribution,\n        address _rewardsToken,\n        address _stakingToken,\n        address _frax_address,\n        address _timelock_address,\n        uint256 _pool_weight\n    ) \n    StakingRewards(_owner, _rewardsDistribution, _rewardsToken, _stakingToken, _frax_address, _timelock_address, _pool_weight)\n    public {}\n}"},"Stake_FXS_WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./StakingRewards.sol\";\n\ncontract Stake_FXS_WETH is StakingRewards {\n    constructor(\n        address _owner,\n        address _rewardsDistribution,\n        address _rewardsToken,\n        address _stakingToken,\n        address _frax_address,\n        address _timelock_address,\n        uint256 _pool_weight\n    ) \n    StakingRewards(_owner, _rewardsDistribution, _rewardsToken, _stakingToken, _frax_address, _timelock_address, _pool_weight)\n    public {}\n}"},"StakingRewards.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\n// Stolen with love from Synthetixio\n// https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol\n\nimport \"./Math.sol\";\nimport \"./SafeMath.sol\";\nimport \"./ERC20.sol\";\nimport \u0027./TransferHelper.sol\u0027;\nimport \"./SafeERC20.sol\";\nimport \"./Frax.sol\";\nimport \"./ReentrancyGuard.sol\";\nimport \"./StringHelpers.sol\";\n\n// Inheritance\nimport \"./IStakingRewards.sol\";\nimport \"./RewardsDistributionRecipient.sol\";\nimport \"./Pausable.sol\";\n\ncontract StakingRewards is IStakingRewards, RewardsDistributionRecipient, ReentrancyGuard, Pausable {\n    using SafeMath for uint256;\n    using SafeERC20 for ERC20;\n\n    /* ========== STATE VARIABLES ========== */\n\n    FRAXStablecoin private FRAX;\n    ERC20 public rewardsToken;\n    ERC20 public stakingToken;\n    uint256 public periodFinish;\n\n    // Constant for various precisions\n    uint256 private constant PRICE_PRECISION = 1e6;\n    uint256 private constant MULTIPLIER_BASE = 1e6;\n\n    // Max reward per second\n    uint256 public rewardRate;\n\n    // uint256 public rewardsDuration = 86400 hours;\n    uint256 public rewardsDuration = 604800; // 7 * 86400  (7 days)\n\n    uint256 public lastUpdateTime;\n    uint256 public rewardPerTokenStored = 0;\n    uint256 private pool_weight; // This staking pool\u0027s percentage of the total FXS being distributed by all pools, 6 decimals of precision\n\n    address public owner_address;\n    address public timelock_address; // Governance timelock address\n\n    uint256 public locked_stake_max_multiplier = 3000000; // 6 decimals of precision. 1x = 1000000\n    uint256 public locked_stake_time_for_max_multiplier = 3 * 365 * 86400; // 3 years\n    uint256 public locked_stake_min_time = 604800; // 7 * 86400  (7 days)\n    string private locked_stake_min_time_str = \"604800\"; // 7 days on genesis\n\n    uint256 public cr_boost_max_multiplier = 3000000; // 6 decimals of precision. 1x = 1000000\n\n    mapping(address =\u003e uint256) public userRewardPerTokenPaid;\n    mapping(address =\u003e uint256) public rewards;\n\n    uint256 private _staking_token_supply = 0;\n    uint256 private _staking_token_boosted_supply = 0;\n    mapping(address =\u003e uint256) private _unlocked_balances;\n    mapping(address =\u003e uint256) private _locked_balances;\n    mapping(address =\u003e uint256) private _boosted_balances;\n\n    mapping(address =\u003e LockedStake[]) private lockedStakes;\n\n    mapping(address =\u003e bool) public greylist;\n\n    bool public unlockedStakes; // Release lock stakes in case of system migration\n\n    struct LockedStake {\n        bytes32 kek_id;\n        uint256 start_timestamp;\n        uint256 amount;\n        uint256 ending_timestamp;\n        uint256 multiplier; // 6 decimals of precision. 1x = 1000000\n    }\n\n    /* ========== CONSTRUCTOR ========== */\n\n    constructor(\n        address _owner,\n        address _rewardsDistribution,\n        address _rewardsToken,\n        address _stakingToken,\n        address _frax_address,\n        address _timelock_address,\n        uint256 _pool_weight\n    ) public Owned(_owner){\n        owner_address = _owner;\n        rewardsToken = ERC20(_rewardsToken);\n        stakingToken = ERC20(_stakingToken);\n        FRAX = FRAXStablecoin(_frax_address);\n        rewardsDistribution = _rewardsDistribution;\n        lastUpdateTime = block.timestamp;\n        timelock_address = _timelock_address;\n        pool_weight = _pool_weight;\n        rewardRate = 380517503805175038; // (uint256(12000000e18)).div(365 * 86400); // Base emission rate of 12M FXS over the first year\n        rewardRate = rewardRate.mul(pool_weight).div(1e6);\n        unlockedStakes = false;\n    }\n\n    /* ========== VIEWS ========== */\n\n    function totalSupply() external override view returns (uint256) {\n        return _staking_token_supply;\n    }\n\n    function totalBoostedSupply() external view returns (uint256) {\n        return _staking_token_boosted_supply;\n    }\n\n    function stakingMultiplier(uint256 secs) public view returns (uint256) {\n        uint256 multiplier = uint(MULTIPLIER_BASE).add(secs.mul(locked_stake_max_multiplier.sub(MULTIPLIER_BASE)).div(locked_stake_time_for_max_multiplier));\n        if (multiplier \u003e locked_stake_max_multiplier) multiplier = locked_stake_max_multiplier;\n        return multiplier;\n    }\n\n    function crBoostMultiplier() public view returns (uint256) {\n        uint256 multiplier = uint(MULTIPLIER_BASE).add((uint(MULTIPLIER_BASE).sub(FRAX.global_collateral_ratio())).mul(cr_boost_max_multiplier.sub(MULTIPLIER_BASE)).div(MULTIPLIER_BASE) );\n        return multiplier;\n    }\n\n    // Total unlocked and locked liquidity tokens\n    function balanceOf(address account) external override view returns (uint256) {\n        return (_unlocked_balances[account]).add(_locked_balances[account]);\n    }\n\n    // Total unlocked liquidity tokens\n    function unlockedBalanceOf(address account) external view returns (uint256) {\n        return _unlocked_balances[account];\n    }\n\n    // Total locked liquidity tokens\n    function lockedBalanceOf(address account) public view returns (uint256) {\n        return _locked_balances[account];\n    }\n\n    // Total \u0027balance\u0027 used for calculating the percent of the pool the account owns\n    // Takes into account the locked stake time multiplier\n    function boostedBalanceOf(address account) external view returns (uint256) {\n        return _boosted_balances[account];\n    }\n\n    function lockedStakesOf(address account) external view returns (LockedStake[] memory) {\n        return lockedStakes[account];\n    }\n\n    function stakingDecimals() external view returns (uint256) {\n        return stakingToken.decimals();\n    }\n\n    function rewardsFor(address account) external view returns (uint256) {\n        // You may have use earned() instead, because of the order in which the contract executes \n        return rewards[account];\n    }\n\n    function lastTimeRewardApplicable() public override view returns (uint256) {\n        return Math.min(block.timestamp, periodFinish);\n    }\n\n    function rewardPerToken() public override view returns (uint256) {\n        if (_staking_token_supply == 0) {\n            return rewardPerTokenStored;\n        }\n        else {\n            return rewardPerTokenStored.add(\n                lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(crBoostMultiplier()).mul(1e18).div(PRICE_PRECISION).div(_staking_token_boosted_supply)\n            );\n        }\n    }\n\n    function earned(address account) public override view returns (uint256) {\n        return _boosted_balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);\n    }\n\n    // function earned(address account) public override view returns (uint256) {\n    //     return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).add(rewards[account]);\n    // }\n\n    function getRewardForDuration() external override view returns (uint256) {\n        return rewardRate.mul(rewardsDuration).mul(crBoostMultiplier()).div(PRICE_PRECISION);\n    }\n\n    /* ========== MUTATIVE FUNCTIONS ========== */\n\n    function stake(uint256 amount) external override nonReentrant notPaused updateReward(msg.sender) {\n        require(amount \u003e 0, \"Cannot stake 0\");\n        require(greylist[msg.sender] == false, \"address has been greylisted\");\n\n        // Pull the tokens from the staker\n        TransferHelper.safeTransferFrom(address(stakingToken), msg.sender, address(this), amount);\n\n        // Staking token supply and boosted supply\n        _staking_token_supply = _staking_token_supply.add(amount);\n        _staking_token_boosted_supply = _staking_token_boosted_supply.add(amount);\n\n        // Staking token balance and boosted balance\n        _unlocked_balances[msg.sender] = _unlocked_balances[msg.sender].add(amount);\n        _boosted_balances[msg.sender] = _boosted_balances[msg.sender].add(amount);\n\n        emit Staked(msg.sender, amount);\n    }\n\n    function stakeLocked(uint256 amount, uint256 secs) external nonReentrant notPaused updateReward(msg.sender) {\n        require(amount \u003e 0, \"Cannot stake 0\");\n        require(secs \u003e 0, \"Cannot wait for a negative number\");\n        require(greylist[msg.sender] == false, \"address has been greylisted\");\n        require(secs \u003e= locked_stake_min_time, StringHelpers.strConcat(\"Minimum stake time not met (\", locked_stake_min_time_str, \")\") );\n\n        uint256 multiplier = stakingMultiplier(secs);\n        uint256 boostedAmount = amount.mul(multiplier).div(PRICE_PRECISION);\n        lockedStakes[msg.sender].push(LockedStake(\n            keccak256(abi.encodePacked(msg.sender, block.timestamp, amount)),\n            block.timestamp,\n            amount,\n            block.timestamp.add(secs),\n            multiplier\n        ));\n\n        // Pull the tokens from the staker\n        TransferHelper.safeTransferFrom(address(stakingToken), msg.sender, address(this), amount);\n\n        // Staking token supply and boosted supply\n        _staking_token_supply = _staking_token_supply.add(amount);\n        _staking_token_boosted_supply = _staking_token_boosted_supply.add(boostedAmount);\n\n        // Staking token balance and boosted balance\n        _locked_balances[msg.sender] = _locked_balances[msg.sender].add(amount);\n        _boosted_balances[msg.sender] = _boosted_balances[msg.sender].add(boostedAmount);\n\n        emit StakeLocked(msg.sender, amount, secs);\n    }\n\n    function withdraw(uint256 amount) public override nonReentrant updateReward(msg.sender) {\n        require(amount \u003e 0, \"Cannot withdraw 0\");\n\n        // Staking token balance and boosted balance\n        _unlocked_balances[msg.sender] = _unlocked_balances[msg.sender].sub(amount);\n        _boosted_balances[msg.sender] = _boosted_balances[msg.sender].sub(amount);\n\n        // Staking token supply and boosted supply\n        _staking_token_supply = _staking_token_supply.sub(amount);\n        _staking_token_boosted_supply = _staking_token_boosted_supply.sub(amount);\n\n        // Give the tokens to the withdrawer\n        stakingToken.safeTransfer(msg.sender, amount);\n        emit Withdrawn(msg.sender, amount);\n    }\n\n    function withdrawLocked(bytes32 kek_id) public nonReentrant updateReward(msg.sender) {\n        LockedStake memory thisStake;\n        thisStake.amount = 0;\n        uint theIndex;\n        for (uint i = 0; i \u003c lockedStakes[msg.sender].length; i++){ \n            if (kek_id == lockedStakes[msg.sender][i].kek_id){\n                thisStake = lockedStakes[msg.sender][i];\n                theIndex = i;\n                break;\n            }\n        }\n        require(thisStake.kek_id == kek_id, \"Stake not found\");\n        require(block.timestamp \u003e= thisStake.ending_timestamp || unlockedStakes == true, \"Stake is still locked!\");\n\n        uint256 theAmount = thisStake.amount;\n        uint256 boostedAmount = theAmount.mul(thisStake.multiplier).div(PRICE_PRECISION);\n        if (theAmount \u003e 0){\n            // Staking token balance and boosted balance\n            _locked_balances[msg.sender] = _locked_balances[msg.sender].sub(theAmount);\n            _boosted_balances[msg.sender] = _boosted_balances[msg.sender].sub(boostedAmount);\n\n            // Staking token supply and boosted supply\n            _staking_token_supply = _staking_token_supply.sub(theAmount);\n            _staking_token_boosted_supply = _staking_token_boosted_supply.sub(boostedAmount);\n\n            // Remove the stake from the array\n            delete lockedStakes[msg.sender][theIndex];\n\n            // Give the tokens to the withdrawer\n            stakingToken.safeTransfer(msg.sender, theAmount);\n\n            emit WithdrawnLocked(msg.sender, theAmount, kek_id);\n        }\n\n    }\n\n    function getReward() public override nonReentrant updateReward(msg.sender) {\n        uint256 reward = rewards[msg.sender];\n        if (reward \u003e 0) {\n            rewards[msg.sender] = 0;\n            rewardsToken.transfer(msg.sender, reward);\n            emit RewardPaid(msg.sender, reward);\n        }\n    }\n/*\n    function exit() external override {\n        withdraw(_balances[msg.sender]);\n\n        // TODO: Add locked stakes too?\n\n        getReward();\n    }\n*/\n    function renewIfApplicable() external {\n        if (block.timestamp \u003e periodFinish) {\n            retroCatchUp();\n        }\n    }\n\n    // If the period expired, renew it\n    function retroCatchUp() internal {\n        // Failsafe check\n        require(block.timestamp \u003e periodFinish, \"Period has not expired yet!\");\n\n        // Ensure the provided reward amount is not more than the balance in the contract.\n        // This keeps the reward rate in the right range, preventing overflows due to\n        // very high values of rewardRate in the earned and rewardsPerToken functions;\n        // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.\n        uint256 num_periods_elapsed = uint256(block.timestamp.sub(periodFinish)) / rewardsDuration; // Floor division to the nearest period\n        uint balance = rewardsToken.balanceOf(address(this));\n        require(rewardRate.mul(rewardsDuration).mul(crBoostMultiplier()).mul(num_periods_elapsed + 1).div(PRICE_PRECISION) \u003c= balance, \"Not enough FXS available for rewards!\");\n\n        // uint256 old_lastUpdateTime = lastUpdateTime;\n        // uint256 new_lastUpdateTime = block.timestamp;\n\n        // lastUpdateTime = periodFinish;\n        periodFinish = periodFinish.add((num_periods_elapsed.add(1)).mul(rewardsDuration));\n\n        rewardPerTokenStored = rewardPerToken();\n        lastUpdateTime = lastTimeRewardApplicable();\n\n        emit RewardsPeriodRenewed(address(stakingToken));\n    }\n\n    /* ========== RESTRICTED FUNCTIONS ========== */\n/*\n    // This notifies people that the reward is being changed\n    function notifyRewardAmount(uint256 reward) external override onlyRewardsDistribution updateReward(address(0)) {\n        // Needed to make compiler happy\n\n        \n        // if (block.timestamp \u003e= periodFinish) {\n        //     rewardRate = reward.mul(crBoostMultiplier()).div(rewardsDuration).div(PRICE_PRECISION);\n        // } else {\n        //     uint256 remaining = periodFinish.sub(block.timestamp);\n        //     uint256 leftover = remaining.mul(rewardRate);\n        //     rewardRate = reward.mul(crBoostMultiplier()).add(leftover).div(rewardsDuration).div(PRICE_PRECISION);\n        // }\n\n        // // Ensure the provided reward amount is not more than the balance in the contract.\n        // // This keeps the reward rate in the right range, preventing overflows due to\n        // // very high values of rewardRate in the earned and rewardsPerToken functions;\n        // // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.\n        // uint balance = rewardsToken.balanceOf(address(this));\n        // require(rewardRate \u003c= balance.div(rewardsDuration), \"Provided reward too high\");\n\n        // lastUpdateTime = block.timestamp;\n        // periodFinish = block.timestamp.add(rewardsDuration);\n        // emit RewardAdded(reward);\n    }\n*/\n    // Added to support recovering LP Rewards from other systems to be distributed to holders\n    function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance {\n        // Admin cannot withdraw the staking token from the contract\n        require(tokenAddress != address(stakingToken));\n        ERC20(tokenAddress).transfer(owner_address, tokenAmount);\n        emit Recovered(tokenAddress, tokenAmount);\n    }\n\n    function setRewardsDuration(uint256 _rewardsDuration) external onlyByOwnerOrGovernance {\n        require(\n            periodFinish == 0 || block.timestamp \u003e periodFinish,\n            \"Previous rewards period must be complete before changing the duration for the new period\"\n        );\n        rewardsDuration = _rewardsDuration;\n        emit RewardsDurationUpdated(rewardsDuration);\n    }\n\n    function setMultipliers(uint256 _locked_stake_max_multiplier, uint256 _cr_boost_max_multiplier) external onlyByOwnerOrGovernance {\n        require(_locked_stake_max_multiplier \u003e= 1, \"Multiplier must be greater than or equal to 1\");\n        require(_cr_boost_max_multiplier \u003e= 1, \"Max CR Boost must be greater than or equal to 1\");\n\n        locked_stake_max_multiplier = _locked_stake_max_multiplier;\n        cr_boost_max_multiplier = _cr_boost_max_multiplier;\n        \n        emit MaxCRBoostMultiplier(cr_boost_max_multiplier);\n        emit LockedStakeMaxMultiplierUpdated(locked_stake_max_multiplier);\n    }\n\n    function setLockedStakeTimeForMinAndMaxMultiplier(uint256 _locked_stake_time_for_max_multiplier, uint256 _locked_stake_min_time) external onlyByOwnerOrGovernance {\n        require(_locked_stake_time_for_max_multiplier \u003e= 1, \"Multiplier Max Time must be greater than or equal to 1\");\n        require(_locked_stake_min_time \u003e= 1, \"Multiplier Min Time must be greater than or equal to 1\");\n        \n        locked_stake_time_for_max_multiplier = _locked_stake_time_for_max_multiplier;\n\n        locked_stake_min_time = _locked_stake_min_time;\n        locked_stake_min_time_str = StringHelpers.uint2str(_locked_stake_min_time);\n\n        emit LockedStakeTimeForMaxMultiplier(locked_stake_time_for_max_multiplier);\n        emit LockedStakeMinTime(_locked_stake_min_time);\n    }\n\n    function initializeDefault() external onlyByOwnerOrGovernance {\n        lastUpdateTime = block.timestamp;\n        periodFinish = block.timestamp.add(rewardsDuration);\n        emit DefaultInitialization();\n    }\n\n    function greylistAddress(address _address) external onlyByOwnerOrGovernance {\n        greylist[_address] = !(greylist[_address]);\n    }\n\n    function unlockStakes() external onlyByOwnerOrGovernance {\n        unlockedStakes = !unlockedStakes;\n    }\n\n    function setRewardRate(uint256 _new_rate) external onlyByOwnerOrGovernance {\n        rewardRate = _new_rate;\n    }\n\n    function setOwnerAndTimelock(address _new_owner, address _new_timelock) external onlyByOwnerOrGovernance {\n        owner_address = _new_owner;\n        timelock_address = _new_timelock;\n    }\n\n    /* ========== MODIFIERS ========== */\n\n    modifier updateReward(address account) {\n        // Need to retro-adjust some things if the period hasn\u0027t been renewed, then start a new one\n        if (block.timestamp \u003e periodFinish) {\n            retroCatchUp();\n        }\n        else {\n            rewardPerTokenStored = rewardPerToken();\n            lastUpdateTime = lastTimeRewardApplicable();\n        }\n        if (account != address(0)) {\n            rewards[account] = earned(account);\n            userRewardPerTokenPaid[account] = rewardPerTokenStored;\n        }\n        _;\n    }\n\n    modifier onlyByOwnerOrGovernance() {\n        require(msg.sender == owner_address || msg.sender == timelock_address, \"You are not the owner or the governance timelock\");\n        _;\n    }\n\n    /* ========== EVENTS ========== */\n\n    event RewardAdded(uint256 reward);\n    event Staked(address indexed user, uint256 amount);\n    event StakeLocked(address indexed user, uint256 amount, uint256 secs);\n    event Withdrawn(address indexed user, uint256 amount);\n    event WithdrawnLocked(address indexed user, uint256 amount, bytes32 kek_id);\n    event RewardPaid(address indexed user, uint256 reward);\n    event RewardsDurationUpdated(uint256 newDuration);\n    event Recovered(address token, uint256 amount);\n    event RewardsPeriodRenewed(address token);\n    event DefaultInitialization();\n    event LockedStakeMaxMultiplierUpdated(uint256 multiplier);\n    event LockedStakeTimeForMaxMultiplier(uint256 secs);\n    event LockedStakeMinTime(uint256 secs);\n    event MaxCRBoostMultiplier(uint256 multiplier);\n}\n"},"StringHelpers.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n\nlibrary StringHelpers {\n    function parseAddr(string memory _a) internal pure returns (address _parsedAddress) {\n        bytes memory tmp = bytes(_a);\n        uint160 iaddr = 0;\n        uint160 b1;\n        uint160 b2;\n        for (uint i = 2; i \u003c 2 + 2 * 20; i += 2) {\n            iaddr *= 256;\n            b1 = uint160(uint8(tmp[i]));\n            b2 = uint160(uint8(tmp[i + 1]));\n            if ((b1 \u003e= 97) \u0026\u0026 (b1 \u003c= 102)) {\n                b1 -= 87;\n            } else if ((b1 \u003e= 65) \u0026\u0026 (b1 \u003c= 70)) {\n                b1 -= 55;\n            } else if ((b1 \u003e= 48) \u0026\u0026 (b1 \u003c= 57)) {\n                b1 -= 48;\n            }\n            if ((b2 \u003e= 97) \u0026\u0026 (b2 \u003c= 102)) {\n                b2 -= 87;\n            } else if ((b2 \u003e= 65) \u0026\u0026 (b2 \u003c= 70)) {\n                b2 -= 55;\n            } else if ((b2 \u003e= 48) \u0026\u0026 (b2 \u003c= 57)) {\n                b2 -= 48;\n            }\n            iaddr += (b1 * 16 + b2);\n        }\n        return address(iaddr);\n    }\n\n    function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) {\n        bytes memory a = bytes(_a);\n        bytes memory b = bytes(_b);\n        uint minLength = a.length;\n        if (b.length \u003c minLength) {\n            minLength = b.length;\n        }\n        for (uint i = 0; i \u003c minLength; i ++) {\n            if (a[i] \u003c b[i]) {\n                return -1;\n            } else if (a[i] \u003e b[i]) {\n                return 1;\n            }\n        }\n        if (a.length \u003c b.length) {\n            return -1;\n        } else if (a.length \u003e b.length) {\n            return 1;\n        } else {\n            return 0;\n        }\n    }\n\n    function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) {\n        bytes memory h = bytes(_haystack);\n        bytes memory n = bytes(_needle);\n        if (h.length \u003c 1 || n.length \u003c 1 || (n.length \u003e h.length)) {\n            return -1;\n        } else if (h.length \u003e (2 ** 128 - 1)) {\n            return -1;\n        } else {\n            uint subindex = 0;\n            for (uint i = 0; i \u003c h.length; i++) {\n                if (h[i] == n[0]) {\n                    subindex = 1;\n                    while(subindex \u003c n.length \u0026\u0026 (i + subindex) \u003c h.length \u0026\u0026 h[i + subindex] == n[subindex]) {\n                        subindex++;\n                    }\n                    if (subindex == n.length) {\n                        return int(i);\n                    }\n                }\n            }\n            return -1;\n        }\n    }\n\n    function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) {\n        return strConcat(_a, _b, \"\", \"\", \"\");\n    }\n\n    function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) {\n        return strConcat(_a, _b, _c, \"\", \"\");\n    }\n\n    function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) {\n        return strConcat(_a, _b, _c, _d, \"\");\n    }\n\n    function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) {\n        bytes memory _ba = bytes(_a);\n        bytes memory _bb = bytes(_b);\n        bytes memory _bc = bytes(_c);\n        bytes memory _bd = bytes(_d);\n        bytes memory _be = bytes(_e);\n        string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);\n        bytes memory babcde = bytes(abcde);\n        uint k = 0;\n        uint i = 0;\n        for (i = 0; i \u003c _ba.length; i++) {\n            babcde[k++] = _ba[i];\n        }\n        for (i = 0; i \u003c _bb.length; i++) {\n            babcde[k++] = _bb[i];\n        }\n        for (i = 0; i \u003c _bc.length; i++) {\n            babcde[k++] = _bc[i];\n        }\n        for (i = 0; i \u003c _bd.length; i++) {\n            babcde[k++] = _bd[i];\n        }\n        for (i = 0; i \u003c _be.length; i++) {\n            babcde[k++] = _be[i];\n        }\n        return string(babcde);\n    }\n\n    function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) {\n        return safeParseInt(_a, 0);\n    }\n\n    function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {\n        bytes memory bresult = bytes(_a);\n        uint mint = 0;\n        bool decimals = false;\n        for (uint i = 0; i \u003c bresult.length; i++) {\n            if ((uint(uint8(bresult[i])) \u003e= 48) \u0026\u0026 (uint(uint8(bresult[i])) \u003c= 57)) {\n                if (decimals) {\n                   if (_b == 0) break;\n                    else _b--;\n                }\n                mint *= 10;\n                mint += uint(uint8(bresult[i])) - 48;\n            } else if (uint(uint8(bresult[i])) == 46) {\n                require(!decimals, \u0027More than one decimal encountered in string!\u0027);\n                decimals = true;\n            } else {\n                revert(\"Non-numeral character encountered in string!\");\n            }\n        }\n        if (_b \u003e 0) {\n            mint *= 10 ** _b;\n        }\n        return mint;\n    }\n\n    function parseInt(string memory _a) internal pure returns (uint _parsedInt) {\n        return parseInt(_a, 0);\n    }\n\n    function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {\n        bytes memory bresult = bytes(_a);\n        uint mint = 0;\n        bool decimals = false;\n        for (uint i = 0; i \u003c bresult.length; i++) {\n            if ((uint(uint8(bresult[i])) \u003e= 48) \u0026\u0026 (uint(uint8(bresult[i])) \u003c= 57)) {\n                if (decimals) {\n                   if (_b == 0) {\n                       break;\n                   } else {\n                       _b--;\n                   }\n                }\n                mint *= 10;\n                mint += uint(uint8(bresult[i])) - 48;\n            } else if (uint(uint8(bresult[i])) == 46) {\n                decimals = true;\n            }\n        }\n        if (_b \u003e 0) {\n            mint *= 10 ** _b;\n        }\n        return mint;\n    }\n\n    function uint2str(uint _i) internal pure returns (string memory _uintAsString) {\n        if (_i == 0) {\n            return \"0\";\n        }\n        uint j = _i;\n        uint len;\n        while (j != 0) {\n            len++;\n            j /= 10;\n        }\n        bytes memory bstr = new bytes(len);\n        uint k = len - 1;\n        while (_i != 0) {\n            bstr[k--] = byte(uint8(48 + _i % 10));\n            _i /= 10;\n        }\n        return string(bstr);\n    }\n}"},"SwapToPrice.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Pair.sol\u0027;\nimport \u0027./Babylonian.sol\u0027;\nimport \u0027./SafeMath.sol\u0027;\nimport \u0027./TransferHelper.sol\u0027;\nimport \u0027./IERC20.sol\u0027;\nimport \u0027./IUniswapV2Router01.sol\u0027;\nimport \u0027./UniswapV2Library.sol\u0027;\n\ncontract SwapToPrice {\n    using SafeMath for uint256;\n\n    IUniswapV2Router01 public immutable router;\n    address public immutable factory;\n\n    constructor(address factory_, IUniswapV2Router01 router_) public {\n        factory = factory_;\n        router = router_;\n    }\n\n    // computes the direction and magnitude of the profit-maximizing trade\n    function computeProfitMaximizingTrade(\n        uint256 truePriceTokenA,\n        uint256 truePriceTokenB,\n        uint256 reserveA,\n        uint256 reserveB\n    ) pure public returns (bool aToB, uint256 amountIn) {\n        aToB = reserveA.mul(truePriceTokenB) / reserveB \u003c truePriceTokenA;\n\n        uint256 invariant = reserveA.mul(reserveB);\n\n        uint256 leftSide = Babylonian.sqrt(\n            invariant.mul(aToB ? truePriceTokenA : truePriceTokenB).mul(1000) /\n            uint256(aToB ? truePriceTokenB : truePriceTokenA).mul(997)\n        );\n        uint256 rightSide = (aToB ? reserveA.mul(1000) : reserveB.mul(1000)) / 997;\n\n        // compute the amount that must be sent to move the price to the profit-maximizing price\n        amountIn = leftSide.sub(rightSide);\n    }\n\n    // swaps an amount of either token such that the trade is profit-maximizing, given an external true price\n    // true price is expressed in the ratio of token A to token B\n    // caller must approve this contract to spend whichever token is intended to be swapped\n    function swapToPrice(\n        address tokenA,\n        address tokenB,\n        uint256 truePriceTokenA,\n        uint256 truePriceTokenB,\n        uint256 maxSpendTokenA,\n        uint256 maxSpendTokenB,\n        address to,\n        uint256 deadline\n    ) public {\n        // true price is expressed as a ratio, so both values must be non-zero\n        require(truePriceTokenA != 0 \u0026\u0026 truePriceTokenB != 0, \"ExampleSwapToPrice: ZERO_PRICE\");\n        // caller can specify 0 for either if they wish to swap in only one direction, but not both\n        require(maxSpendTokenA != 0 || maxSpendTokenB != 0, \"ExampleSwapToPrice: ZERO_SPEND\");\n\n        bool aToB;\n        uint256 amountIn;\n        {\n            (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);\n            (aToB, amountIn) = computeProfitMaximizingTrade(\n                truePriceTokenA, truePriceTokenB,\n                reserveA, reserveB\n            );\n        }\n\n        // spend up to the allowance of the token in\n        uint256 maxSpend = aToB ? maxSpendTokenA : maxSpendTokenB;\n        if (amountIn \u003e maxSpend) {\n            amountIn = maxSpend;\n        }\n\n        address tokenIn = aToB ? tokenA : tokenB;\n        address tokenOut = aToB ? tokenB : tokenA;\n        TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn);\n        TransferHelper.safeApprove(tokenIn, address(router), amountIn);\n\n        address[] memory path = new address[](2);\n        path[0] = tokenIn;\n        path[1] = tokenOut;\n\n        router.swapExactTokensForTokens(\n            amountIn,\n            0, // amountOutMin: we can skip computing this number because the math is tested\n            path,\n            to,\n            deadline\n        );\n    }\n}"},"TestSwap.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./FakeCollateral_USDT.sol\";\nimport \"./FakeCollateral_WETH.sol\";\nimport \"./UniswapV2Router02_Modified.sol\";\n\n/* IGNORE THIS CONTRACT, ONLY USED FOR TESTING PURPOSES */\n\ncontract TestSwap {\n\taddress public USDT_address;\n\taddress public WETH_address;\n\tUniswapV2Router02_Modified public router;\n\tFakeCollateral_USDT USDT = FakeCollateral_USDT(USDT);\n\tFakeCollateral_WETH WETH = FakeCollateral_WETH(WETH);\n\n\tconstructor( \n\t\taddress _USDT_address, \n\t\taddress _WETH_address,\n\t\tUniswapV2Router02_Modified _router_address\n\t) public {\n\t\tUSDT_address = _USDT_address;\n\t\tWETH_address = _WETH_address;\n\t\trouter = UniswapV2Router02_Modified(_router_address);\n\t}\n\n\tfunction getPath() public returns (address[] memory) {\n\t\taddress[] memory path = new address[](2);\n\t\tpath[0] = USDT_address;\n\t\tpath[1] = WETH_address;\n\t\treturn path;\n\t}\n\n\tfunction swapUSDTforETH(uint256 amountIn, uint256 amountOutMin) public payable {\n\t\trequire(USDT.transferFrom(msg.sender, address(this), amountIn), \"transferFrom failed.\");\n\t\trequire(USDT.approve(address(router), amountIn), \"approve failed.\");\n\n\t\taddress[] memory path = new address[](2);\n\t\tpath[0] = USDT_address;\n\t\tpath[1] = WETH_address;\n\n\t\trouter.swapExactTokensForETH(amountIn, amountOutMin, path, msg.sender, block.timestamp);\n\t}\n\n}"},"Timelock.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./SafeMath.sol\";\n\ncontract Timelock {\n    using SafeMath for uint;\n\n    event NewAdmin(address indexed newAdmin);\n    event NewPendingAdmin(address indexed newPendingAdmin);\n    event NewDelay(uint indexed newDelay);\n    event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature,  bytes data, uint eta);\n    event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature,  bytes data, uint eta);\n    event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);\n\n    uint public constant GRACE_PERIOD = 14 days;\n    uint public constant MINIMUM_DELAY = 2 days;\n    uint public constant MAXIMUM_DELAY = 30 days;\n\n    address public admin;\n    address public pendingAdmin;\n    uint public delay;\n\n    mapping (bytes32 =\u003e bool) public queuedTransactions;\n\n\n    constructor(address admin_, uint delay_) public {\n        require(delay_ \u003e= MINIMUM_DELAY, \"Timelock::constructor: Delay must exceed minimum delay.\");\n        require(delay_ \u003c= MAXIMUM_DELAY, \"Timelock::setDelay: Delay must not exceed maximum delay.\");\n\n        admin = admin_;\n        delay = delay_;\n    }\n\n    //function() external payable { }\n\n    function setDelay(uint delay_) public {\n        require(msg.sender == address(this), \"Timelock::setDelay: Call must come from Timelock.\");\n        require(delay_ \u003e= MINIMUM_DELAY, \"Timelock::setDelay: Delay must exceed minimum delay.\");\n        require(delay_ \u003c= MAXIMUM_DELAY, \"Timelock::setDelay: Delay must not exceed maximum delay.\");\n        delay = delay_;\n\n        emit NewDelay(delay);\n    }\n\n    function acceptAdmin() public {\n        require(msg.sender == pendingAdmin, \"Timelock::acceptAdmin: Call must come from pendingAdmin.\");\n        admin = msg.sender;\n        pendingAdmin = address(0);\n\n        emit NewAdmin(admin);\n    }\n\n    function setPendingAdmin(address pendingAdmin_) public {\n        require(msg.sender == address(this), \"Timelock::setPendingAdmin: Call must come from Timelock.\");\n        pendingAdmin = pendingAdmin_;\n\n        emit NewPendingAdmin(pendingAdmin);\n    }\n\n    function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {\n        require(msg.sender == admin, \"Timelock::queueTransaction: Call must come from admin.\");\n        require(eta \u003e= getBlockTimestamp().add(delay), \"Timelock::queueTransaction: Estimated execution block must satisfy delay.\");\n\n        bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n        queuedTransactions[txHash] = true;\n\n        emit QueueTransaction(txHash, target, value, signature, data, eta);\n        return txHash;\n    }\n\n    function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public {\n        require(msg.sender == admin, \"Timelock::cancelTransaction: Call must come from admin.\");\n\n        bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n        queuedTransactions[txHash] = false;\n\n        emit CancelTransaction(txHash, target, value, signature, data, eta);\n    }\n\n    function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) {\n        require(msg.sender == admin, \"Timelock::executeTransaction: Call must come from admin.\");\n\n        bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n        require(queuedTransactions[txHash], \"Timelock::executeTransaction: Transaction hasn\u0027t been queued.\");\n        require(getBlockTimestamp() \u003e= eta, \"Timelock::executeTransaction: Transaction hasn\u0027t surpassed time lock.\");\n        require(getBlockTimestamp() \u003c= eta.add(GRACE_PERIOD), \"Timelock::executeTransaction: Transaction is stale.\");\n\n        queuedTransactions[txHash] = false;\n\n        bytes memory callData;\n\n        if (bytes(signature).length == 0) {\n            callData = data;\n        } else {\n            callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);\n        }\n\n        // Execute the call\n        (bool success, bytes memory returnData) = target.call{ value: value }(callData);\n        require(success, \"Timelock::executeTransaction: Transaction execution reverted.\");\n\n        emit ExecuteTransaction(txHash, target, value, signature, data, eta);\n\n        return returnData;\n    }\n\n    function getBlockTimestamp() internal view returns (uint) {\n        return block.timestamp;\n    }\n}"},"TokenVesting.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./ERC20Custom.sol\";\nimport \"./ERC20.sol\";\nimport \"./SafeMath.sol\";\n\n/**\n * @title TokenVesting\n * @dev A token holder contract that can release its token balance gradually like a\n * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the\n * owner.\n * \n * Modified from OpenZeppelin\u0027s TokenVesting.sol draft\n */\ncontract TokenVesting {\n    // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is\n    // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,\n    // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a\n    // cliff period of a year and a duration of four years, are safe to use.\n    // solhint-disable not-rely-on-time\n\n    using SafeMath for uint256;\n\n    event TokensReleased(uint256 amount);\n    event TokenVestingRevoked();\n\n    // beneficiary of tokens after they are released\n    address private _beneficiary;\n\n    // owner (grantor) of the tokens\n    address private _owner;\n\n    // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.\n    uint256 private _cliff;\n    uint256 private _start;\n    uint256 private _duration;\n\n    address public _FXS_contract_address;\n    ERC20 FXS;\n    address public _timelock_address;\n    bool public _revocable;\n\n    uint256 private _released;\n    bool public _revoked;\n\n    /**\n     * @dev Creates a vesting contract that vests its balance of any ERC20 token to the\n     * beneficiary, gradually in a linear fashion until start + duration. By then all\n     * of the balance will have vested.\n     * @param beneficiary address of the beneficiary to whom vested tokens are transferred\n     * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest\n     * @param start the time (as Unix time) at which point vesting starts\n     * @param duration duration in seconds of the period in which the tokens will vest\n     * @param revocable whether the vesting is revocable or not\n     */\n\n    constructor(\n        address beneficiary,\n        uint256 start,\n        uint256 cliffDuration,\n        uint256 duration,\n        bool revocable\n    ) public {\n        require(beneficiary != address(0), \"TokenVesting: beneficiary is the zero address\");\n        // solhint-disable-next-line max-line-length\n        require(cliffDuration \u003c= duration, \"TokenVesting: cliff is longer than duration\");\n        require(duration \u003e 0, \"TokenVesting: duration is 0\");\n        // solhint-disable-next-line max-line-length\n        require(start.add(duration) \u003e block.timestamp, \"TokenVesting: final time is before current time\");\n\n        _beneficiary = beneficiary;\n        _revocable = revocable;\n        _duration = duration;\n        _cliff = start.add(cliffDuration);\n        _start = start;\n        _owner = msg.sender;\n    }\n\n    function setFXSAddress(address FXS_address) public {\n        require(msg.sender == _owner, \"must be set by the owner\");\n        _FXS_contract_address = FXS_address;\n        FXS = ERC20(FXS_address);\n    }\n\n    function setTimelockAddress(address timelock_address) public {\n        require(msg.sender == _owner, \"must be set by the owner\");\n        _timelock_address = timelock_address;\n    }\n\n    /**\n     * @return the beneficiary of the tokens.\n     */\n    function getBeneficiary() public view returns (address) {\n        return _beneficiary;\n    }\n\n    /**\n     * @return the cliff time of the token vesting.\n     */\n    function getCliff() public view returns (uint256) {\n        return _cliff;\n    }\n\n    /**\n     * @return the start time of the token vesting.\n     */\n    function getStart() public view returns (uint256) {\n        return _start;\n    }\n\n    /**\n     * @return the duration of the token vesting.\n     */\n    function getDuration() public view returns (uint256) {\n        return _duration;\n    }\n\n    /**\n     * @return true if the vesting is revocable.\n     */\n    function getRevocable() public view returns (bool) {\n        return _revocable;\n    }\n\n    /**\n     * @return the amount of the token released.\n     */\n    function getReleased() public view returns (uint256) {\n        return _released;\n    }\n\n    /**\n     * @return true if the token is revoked.\n     */\n    function getRevoked() public view returns (bool) {\n        return _revoked;\n    }\n\n    /**\n     * @notice Transfers vested tokens to beneficiary.\n     */\n    function release() public {\n        require(msg.sender == _beneficiary, \"must be the beneficiary to release tokens\");\n        uint256 unreleased = _releasableAmount();\n\n        require(unreleased \u003e 0, \"TokenVesting: no tokens are due\");\n\n        _released = _released.add(unreleased);\n\n        FXS.transfer(_beneficiary, unreleased);\n\n        emit TokensReleased(unreleased);\n    }\n\n    /**\n     * @notice Allows the owner to revoke the vesting. Tokens already vested\n     * remain in the contract, the rest are returned to the owner.\n     */\n    function revoke() public {\n        require(msg.sender == _timelock_address, \"Must be called by the timelock contract\");\n        require(_revocable, \"TokenVesting: cannot revoke\");\n        require(!_revoked, \"TokenVesting: token already revoked\");\n\n        uint256 balance = FXS.balanceOf(address(this));\n\n        uint256 unreleased = _releasableAmount();\n        uint256 refund = balance.sub(unreleased);\n\n        _revoked = true;\n\n        FXS.transfer(_owner, refund);\n\n        emit TokenVestingRevoked();\n    }\n\n    // Added to support recovering possible airdrops\n    function recoverERC20(address tokenAddress, uint256 tokenAmount) external {\n        require(msg.sender == _beneficiary, \"Must be called by the beneficiary\");\n\n        // Cannot recover the staking token or the rewards token\n        require(tokenAddress != _FXS_contract_address, \"Cannot withdraw the FXS through this function\");\n        ERC20(tokenAddress).transfer(_beneficiary, tokenAmount);\n    }\n\n\n    /**\n     * @dev Calculates the amount that has already vested but hasn\u0027t been released yet.\n     */\n    function _releasableAmount() private view returns (uint256) {\n        return _vestedAmount().sub(_released);\n    }\n\n    /**\n     * @dev Calculates the amount that has already vested.\n     */\n    function _vestedAmount() private view returns (uint256) {\n        uint256 currentBalance = FXS.balanceOf(address(this));\n        uint256 totalBalance = currentBalance.add(_released);\n        if (block.timestamp \u003c _cliff) {\n            return 0;\n        } else if (block.timestamp \u003e= _start.add(_duration) || _revoked) {\n            return totalBalance;\n        } else {\n            return totalBalance.mul(block.timestamp.sub(_start)).div(_duration);\n        }\n    }\n\n    uint256[44] private __gap;\n}\n"},"TransferHelper.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false\nlibrary TransferHelper {\n    function safeApprove(address token, address to, uint value) internal {\n        // bytes4(keccak256(bytes(\u0027approve(address,uint256)\u0027)));\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));\n        require(success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))), \u0027TransferHelper: APPROVE_FAILED\u0027);\n    }\n\n    function safeTransfer(address token, address to, uint value) internal {\n        // bytes4(keccak256(bytes(\u0027transfer(address,uint256)\u0027)));\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));\n        require(success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))), \u0027TransferHelper: TRANSFER_FAILED\u0027);\n    }\n\n    function safeTransferFrom(address token, address from, address to, uint value) internal {\n        // bytes4(keccak256(bytes(\u0027transferFrom(address,address,uint256)\u0027)));\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));\n        require(success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))), \u0027TransferHelper: TRANSFER_FROM_FAILED\u0027);\n    }\n\n    function safeTransferETH(address to, uint value) internal {\n        (bool success,) = to.call{value:value}(new bytes(0));\n        require(success, \u0027TransferHelper: ETH_TRANSFER_FAILED\u0027);\n    }\n}"},"UniswapPairOracle.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Factory.sol\u0027;\nimport \u0027./IUniswapV2Pair.sol\u0027;\nimport \u0027./FixedPoint.sol\u0027;\n\nimport \u0027./UniswapV2OracleLibrary.sol\u0027;\nimport \u0027./UniswapV2Library.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle {\n    using FixedPoint for *;\n    \n    address owner_address;\n    address timelock_address;\n\n    uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price)\n\n    IUniswapV2Pair public immutable pair;\n    address public immutable token0;\n    address public immutable token1;\n\n    uint    public price0CumulativeLast;\n    uint    public price1CumulativeLast;\n    uint32  public blockTimestampLast;\n    FixedPoint.uq112x112 public price0Average;\n    FixedPoint.uq112x112 public price1Average;\n\n    modifier onlyByOwnerOrGovernance() {\n        require(msg.sender == owner_address || msg.sender == timelock_address, \"You are not an owner or the governance timelock\");\n        _;\n    }\n\n    constructor(address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public {\n        IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));\n        pair = _pair;\n        token0 = _pair.token0();\n        token1 = _pair.token1();\n        price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0)\n        price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1)\n        uint112 reserve0;\n        uint112 reserve1;\n        (reserve0, reserve1, blockTimestampLast) = _pair.getReserves();\n        require(reserve0 != 0 \u0026\u0026 reserve1 != 0, \u0027UniswapPairOracle: NO_RESERVES\u0027); // Ensure that there\u0027s liquidity in the pair\n\n        owner_address = _owner_address;\n        timelock_address = _timelock_address;\n    }\n\n    function setOwner(address _owner_address) external onlyByOwnerOrGovernance {\n        owner_address = _owner_address;\n    }\n\n    function setTimelock(address _timelock_address) external onlyByOwnerOrGovernance {\n        timelock_address = _timelock_address;\n    }\n\n    function setPeriod(uint _period) external onlyByOwnerOrGovernance {\n        PERIOD = _period;\n    }\n\n    function update() external {\n        (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =\n            UniswapV2OracleLibrary.currentCumulativePrices(address(pair));\n        uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired\n\n        // Ensure that at least one full period has passed since the last update\n        require(timeElapsed \u003e= PERIOD, \u0027UniswapPairOracle: PERIOD_NOT_ELAPSED\u0027);\n\n        // Overflow is desired, casting never truncates\n        // Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed\n        price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed));\n        price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed));\n\n        price0CumulativeLast = price0Cumulative;\n        price1CumulativeLast = price1Cumulative;\n        blockTimestampLast = blockTimestamp;\n    }\n\n    // Note this will always return 0 before update has been called successfully for the first time.\n    function consult(address token, uint amountIn) external view returns (uint amountOut) {\n        if (token == token0) {\n            amountOut = price0Average.mul(amountIn).decode144();\n        } else {\n            require(token == token1, \u0027UniswapPairOracle: INVALID_TOKEN\u0027);\n            amountOut = price1Average.mul(amountIn).decode144();\n        }\n    }\n}\n"},"UniswapPairOracle_FRAX_FXS.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_FRAX_FXS is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}"},"UniswapPairOracle_FRAX_USDC.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_FRAX_USDC is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}\n"},"UniswapPairOracle_FRAX_USDT.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_FRAX_USDT is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address)  \n    public {}\n}\n"},"UniswapPairOracle_FRAX_WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_FRAX_WETH is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}"},"UniswapPairOracle_FXS_USDC.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_FXS_USDC is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}"},"UniswapPairOracle_FXS_USDT.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_FXS_USDT is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}"},"UniswapPairOracle_FXS_WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_FXS_WETH is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}"},"UniswapPairOracle_USDC_WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_USDC_WETH is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}\n"},"UniswapPairOracle_USDT_WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_USDT_WETH is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}\n"},"UniswapV2ERC20.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2ERC20.sol\u0027;\nimport \u0027./SafeMath.sol\u0027;\n\ncontract UniswapV2ERC20 is IUniswapV2ERC20 {\n    using SafeMath for uint;\n\n    string public override constant name = \u0027Uniswap V2\u0027;\n    string public override constant symbol = \u0027UNI-V2\u0027;\n    uint8 public override constant decimals = 18;\n    uint  public override totalSupply;\n    mapping(address =\u003e uint) public override balanceOf;\n    mapping(address =\u003e mapping(address =\u003e uint)) public override allowance;\n\n    bytes32 public override DOMAIN_SEPARATOR;\n    // keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n    bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;\n    mapping(address =\u003e uint) public override nonces;\n\n    event Approval(address indexed owner, address indexed spender, uint value);\n    event Transfer(address indexed from, address indexed to, uint value);\n\n    constructor() public {\n        uint chainId;\n        assembly {\n            chainId := chainid()\n        }\n        DOMAIN_SEPARATOR = keccak256(\n            abi.encode(\n                keccak256(\u0027EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\u0027),\n                keccak256(bytes(name)),\n                keccak256(bytes(\u00271\u0027)),\n                chainId,\n                address(this)\n            )\n        );\n    }\n\n    function _mint(address to, uint value) internal {\n        totalSupply = totalSupply.add(value);\n        balanceOf[to] = balanceOf[to].add(value);\n        emit Transfer(address(0), to, value);\n    }\n\n    function _burn(address from, uint value) internal {\n        balanceOf[from] = balanceOf[from].sub(value);\n        totalSupply = totalSupply.sub(value);\n        emit Transfer(from, address(0), value);\n    }\n\n    function _approve(address owner, address spender, uint value) private {\n        allowance[owner][spender] = value;\n        emit Approval(owner, spender, value);\n    }\n\n    function _transfer(address from, address to, uint value) private {\n        balanceOf[from] = balanceOf[from].sub(value);\n        balanceOf[to] = balanceOf[to].add(value);\n        emit Transfer(from, to, value);\n    }\n\n    function approve(address spender, uint value) external override returns (bool) {\n        _approve(msg.sender, spender, value);\n        return true;\n    }\n\n    function transfer(address to, uint value) external override returns (bool) {\n        _transfer(msg.sender, to, value);\n        return true;\n    }\n\n    function transferFrom(address from, address to, uint value) external override returns (bool) {\n        if (allowance[from][msg.sender] != uint(-1)) {\n            allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);\n        }\n        _transfer(from, to, value);\n        return true;\n    }\n\n    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {\n        require(deadline \u003e= block.timestamp, \u0027UniswapV2: EXPIRED\u0027);\n        bytes32 digest = keccak256(\n            abi.encodePacked(\n                \u0027\\x19\\x01\u0027,\n                DOMAIN_SEPARATOR,\n                keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))\n            )\n        );\n        address recoveredAddress = ecrecover(digest, v, r, s);\n        require(recoveredAddress != address(0) \u0026\u0026 recoveredAddress == owner, \u0027UniswapV2: INVALID_SIGNATURE\u0027);\n        _approve(owner, spender, value);\n    }\n}\n"},"UniswapV2Factory.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Factory.sol\u0027;\nimport \u0027./UniswapV2Pair.sol\u0027;\n\ncontract UniswapV2Factory is IUniswapV2Factory {\n    address public override feeTo;\n    address public override feeToSetter;\n\n    mapping(address =\u003e mapping(address =\u003e address)) public override getPair;\n    address[] public override allPairs;\n\n    event PairCreated(address indexed token0, address indexed token1, address pair, uint);\n\n    constructor(address _feeToSetter) public {\n        feeToSetter = _feeToSetter;\n    }\n\n    function allPairsLength() external override view returns (uint) {\n        return allPairs.length;\n    }\n\n    function createPair(address tokenA, address tokenB) external override returns (address pair) {\n        require(tokenA != tokenB, \u0027UniswapV2: IDENTICAL_ADDRESSES\u0027);\n        (address token0, address token1) = tokenA \u003c tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n        require(token0 != address(0), \u0027UniswapV2: ZERO_ADDRESS\u0027);\n        require(getPair[token0][token1] == address(0), \u0027UniswapV2: PAIR_EXISTS\u0027); // single check is sufficient\n        bytes memory bytecode = type(UniswapV2Pair).creationCode;\n        bytes32 salt = keccak256(abi.encodePacked(token0, token1));\n\n        // This creates a new contract\n        assembly {\n            pair := create2(0, add(bytecode, 32), mload(bytecode), salt)\n        }\n        IUniswapV2Pair(pair).initialize(token0, token1);\n        getPair[token0][token1] = pair;\n        getPair[token1][token0] = pair; // populate mapping in the reverse direction\n        allPairs.push(pair);\n        emit PairCreated(token0, token1, pair, allPairs.length);\n    }\n\n    function setFeeTo(address _feeTo) external override {\n        require(msg.sender == feeToSetter, \u0027UniswapV2: FORBIDDEN\u0027);\n        feeTo = _feeTo;\n    }\n\n    function setFeeToSetter(address _feeToSetter) external override {\n        require(msg.sender == feeToSetter, \u0027UniswapV2: FORBIDDEN\u0027);\n        feeToSetter = _feeToSetter;\n    }\n}\n"},"UniswapV2Library.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Pair.sol\u0027;\nimport \u0027./IUniswapV2Factory.sol\u0027;\n\nimport \"./SafeMath.sol\";\n\nlibrary UniswapV2Library {\n    using SafeMath for uint;\n\n    // returns sorted token addresses, used to handle return values from pairs sorted in this order\n    function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {\n        require(tokenA != tokenB, \u0027UniswapV2Library: IDENTICAL_ADDRESSES\u0027);\n        (token0, token1) = tokenA \u003c tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n        require(token0 != address(0), \u0027UniswapV2Library: ZERO_ADDRESS\u0027);\n    }\n\n    // Less efficient than the CREATE2 method below\n    function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) {\n        (address token0, address token1) = sortTokens(tokenA, tokenB);\n        pair = IUniswapV2Factory(factory).getPair(token0, token1);\n    }\n\n    // calculates the CREATE2 address for a pair without making any external calls\n    function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) {\n        (address token0, address token1) = sortTokens(tokenA, tokenB);\n        pair = address(uint(keccak256(abi.encodePacked(\n                hex\u0027ff\u0027,\n                factory,\n                keccak256(abi.encodePacked(token0, token1)),\n                hex\u002796e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f\u0027 // init code hash\n            )))); // this matches the CREATE2 in UniswapV2Factory.createPair\n    }\n\n    // fetches and sorts the reserves for a pair\n    function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {\n        (address token0,) = sortTokens(tokenA, tokenB);\n        (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();\n        (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);\n    }\n\n    // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset\n    function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {\n        require(amountA \u003e 0, \u0027UniswapV2Library: INSUFFICIENT_AMOUNT\u0027);\n        require(reserveA \u003e 0 \u0026\u0026 reserveB \u003e 0, \u0027UniswapV2Library: INSUFFICIENT_LIQUIDITY\u0027);\n        amountB = amountA.mul(reserveB) / reserveA;\n    }\n\n    // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset\n    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {\n        require(amountIn \u003e 0, \u0027UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT\u0027);\n        require(reserveIn \u003e 0 \u0026\u0026 reserveOut \u003e 0, \u0027UniswapV2Library: INSUFFICIENT_LIQUIDITY\u0027);\n        uint amountInWithFee = amountIn.mul(997);\n        uint numerator = amountInWithFee.mul(reserveOut);\n        uint denominator = reserveIn.mul(1000).add(amountInWithFee);\n        amountOut = numerator / denominator;\n    }\n\n    // given an output amount of an asset and pair reserves, returns a required input amount of the other asset\n    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {\n        require(amountOut \u003e 0, \u0027UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        require(reserveIn \u003e 0 \u0026\u0026 reserveOut \u003e 0, \u0027UniswapV2Library: INSUFFICIENT_LIQUIDITY\u0027);\n        uint numerator = reserveIn.mul(amountOut).mul(1000);\n        uint denominator = reserveOut.sub(amountOut).mul(997);\n        amountIn = (numerator / denominator).add(1);\n    }\n\n    // performs chained getAmountOut calculations on any number of pairs\n    function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {\n        require(path.length \u003e= 2, \u0027UniswapV2Library: INVALID_PATH\u0027);\n        amounts = new uint[](path.length);\n        amounts[0] = amountIn;\n        for (uint i; i \u003c path.length - 1; i++) {\n            (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);\n            amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);\n        }\n    }\n\n    // performs chained getAmountIn calculations on any number of pairs\n    function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {\n        require(path.length \u003e= 2, \u0027UniswapV2Library: INVALID_PATH\u0027);\n        amounts = new uint[](path.length);\n        amounts[amounts.length - 1] = amountOut;\n        for (uint i = path.length - 1; i \u003e 0; i--) {\n            (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);\n            amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);\n        }\n    }\n}"},"UniswapV2OracleLibrary.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Pair.sol\u0027;\nimport \u0027./FixedPoint.sol\u0027;\n\n// library with helper methods for oracles that are concerned with computing average prices\nlibrary UniswapV2OracleLibrary {\n    using FixedPoint for *;\n\n    // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]\n    function currentBlockTimestamp() internal view returns (uint32) {\n        return uint32(block.timestamp % 2 ** 32);\n    }\n\n    // produces the cumulative price using counterfactuals to save gas and avoid a call to sync.\n    function currentCumulativePrices(\n        address pair\n    ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {\n        blockTimestamp = currentBlockTimestamp();\n        price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();\n        price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();\n\n        // if time has elapsed since the last update on the pair, mock the accumulated price values\n        (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();\n        if (blockTimestampLast != blockTimestamp) {\n            // subtraction overflow is desired\n            uint32 timeElapsed = blockTimestamp - blockTimestampLast;\n            // addition overflow is desired\n            // counterfactual\n            price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;\n            // counterfactual\n            price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;\n        }\n    }\n}"},"UniswapV2Pair.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n\nimport \u0027./IUniswapV2Pair.sol\u0027;\nimport \u0027./UniswapV2ERC20.sol\u0027;\nimport \u0027./Math.sol\u0027;\nimport \u0027./UQ112x112.sol\u0027;\nimport \u0027./IERC20.sol\u0027;\nimport \u0027./IUniswapV2Factory.sol\u0027;\nimport \u0027./IUniswapV2Callee.sol\u0027;\n\ncontract UniswapV2Pair is IUniswapV2Pair {\n    using SafeMath  for uint;\n    using UQ112x112 for uint224;\n\n    string public override constant name = \u0027Uniswap V2\u0027;\n    string public override constant symbol = \u0027UNI-V2\u0027;\n    uint8 public override constant decimals = 18;\n    uint  public override totalSupply;\n    mapping(address =\u003e uint) public override balanceOf;\n    mapping(address =\u003e mapping(address =\u003e uint)) public override allowance;\n\n    uint public override constant MINIMUM_LIQUIDITY = 10**3;\n    bytes4 private constant SELECTOR = bytes4(keccak256(bytes(\u0027transfer(address,uint256)\u0027)));\n    bytes32 public override DOMAIN_SEPARATOR;\n    // keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n    bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;\n    mapping(address =\u003e uint) public override nonces;\n\n\n    \n\n    address public override factory;\n    address public override token0;\n    address public override token1;\n\n    uint112 private reserve0;           // uses single storage slot, accessible via getReserves\n    uint112 private reserve1;           // uses single storage slot, accessible via getReserves\n    uint32  private blockTimestampLast; // uses single storage slot, accessible via getReserves\n\n    uint public override price0CumulativeLast;\n    uint public override price1CumulativeLast;\n    uint public override kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event\n\n    uint private unlocked = 1;\n    modifier lock() {\n        require(unlocked == 1, \u0027UniswapV2: LOCKED\u0027);\n        unlocked = 0;\n        _;\n        unlocked = 1;\n    }\n\n    function getReserves() public override view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {\n        _reserve0 = reserve0;\n        _reserve1 = reserve1;\n        _blockTimestampLast = blockTimestampLast;\n    }\n\n    function _safeTransfer(address token, address to, uint value) private {\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));\n        require(success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))), \u0027UniswapV2: TRANSFER_FAILED\u0027);\n    }\n\n    event Mint(address indexed sender, uint amount0, uint amount1);\n    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);\n    event Swap(\n        address indexed sender,\n        uint amount0In,\n        uint amount1In,\n        uint amount0Out,\n        uint amount1Out,\n        address indexed to\n    );\n    event Sync(uint112 reserve0, uint112 reserve1);\n\n    constructor() public {\n        factory = msg.sender;\n    }\n\n    // called once by the factory at time of deployment\n    function initialize(address _token0, address _token1) external override {\n        require(msg.sender == factory, \u0027UniswapV2: FORBIDDEN\u0027); // sufficient check\n        token0 = _token0;\n        token1 = _token1;\n    }\n\n    // update reserves and, on the first call per block, price accumulators\n    function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {\n        require(balance0 \u003c= uint112(-1) \u0026\u0026 balance1 \u003c= uint112(-1), \u0027UniswapV2: OVERFLOW\u0027);\n        uint32 blockTimestamp = uint32(block.timestamp % 2**32);\n        uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired\n        if (timeElapsed \u003e 0 \u0026\u0026 _reserve0 != 0 \u0026\u0026 _reserve1 != 0) {\n            // * never overflows, and + overflow is desired\n            price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;\n            price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;\n        }\n        reserve0 = uint112(balance0);\n        reserve1 = uint112(balance1);\n        blockTimestampLast = blockTimestamp;\n        emit Sync(reserve0, reserve1);\n    }\n\n    // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)\n    function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {\n        address feeTo = IUniswapV2Factory(factory).feeTo();\n        feeOn = feeTo != address(0);\n        uint _kLast = kLast; // gas savings\n        if (feeOn) {\n            if (_kLast != 0) {\n                uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));\n                uint rootKLast = Math.sqrt(_kLast);\n                if (rootK \u003e rootKLast) {\n                    uint numerator = totalSupply.mul(rootK.sub(rootKLast));\n                    uint denominator = rootK.mul(5).add(rootKLast);\n                    uint liquidity = numerator / denominator;\n                    if (liquidity \u003e 0) _mint(feeTo, liquidity);\n                }\n            }\n        } else if (_kLast != 0) {\n            kLast = 0;\n        }\n    }\n\n    // this low-level function should be called from a contract which performs important safety checks\n    function mint(address to) external override lock returns (uint liquidity) {\n        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings\n        uint balance0 = IERC20(token0).balanceOf(address(this));\n        uint balance1 = IERC20(token1).balanceOf(address(this));\n        uint amount0 = balance0.sub(_reserve0);\n        uint amount1 = balance1.sub(_reserve1);\n        bool feeOn = _mintFee(_reserve0, _reserve1);\n        uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee\n\n        if (_totalSupply == 0) {\n            liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);\n           _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens\n        } else {\n            liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);\n        }\n\n        require(liquidity \u003e 0, \u0027UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED\u0027);\n        _mint(to, liquidity);\n\n        _update(balance0, balance1, _reserve0, _reserve1);\n        if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date\n        emit Mint(msg.sender, amount0, amount1);\n    }\n\n    // this low-level function should be called from a contract which performs important safety checks\n    function burn(address to) external override lock returns (uint amount0, uint amount1) {\n        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings\n        address _token0 = token0;                                // gas savings\n        address _token1 = token1;                                // gas savings\n        uint balance0 = IERC20(_token0).balanceOf(address(this));\n        uint balance1 = IERC20(_token1).balanceOf(address(this));\n        uint liquidity = balanceOf[address(this)];\n\n        bool feeOn = _mintFee(_reserve0, _reserve1);\n        uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee\n        amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution\n        amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution\n        require(amount0 \u003e 0 \u0026\u0026 amount1 \u003e 0, \u0027UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED\u0027);\n        _burn(address(this), liquidity);\n        _safeTransfer(_token0, to, amount0);\n        _safeTransfer(_token1, to, amount1);\n        balance0 = IERC20(_token0).balanceOf(address(this));\n        balance1 = IERC20(_token1).balanceOf(address(this));\n\n        _update(balance0, balance1, _reserve0, _reserve1);\n        if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date\n        emit Burn(msg.sender, amount0, amount1, to);\n    }\n\n    // this low-level function should be called from a contract which performs important safety checks\n    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external override lock {\n        require(amount0Out \u003e 0 || amount1Out \u003e 0, \u0027UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings\n        require(amount0Out \u003c _reserve0 \u0026\u0026 amount1Out \u003c _reserve1, \u0027UniswapV2: INSUFFICIENT_LIQUIDITY\u0027);\n\n        uint balance0;\n        uint balance1;\n        { // scope for _token{0,1}, avoids stack too deep errors\n        address _token0 = token0;\n        address _token1 = token1;\n        require(to != _token0 \u0026\u0026 to != _token1, \u0027UniswapV2: INVALID_TO\u0027);\n        if (amount0Out \u003e 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens\n        if (amount1Out \u003e 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens\n        if (data.length \u003e 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);\n        balance0 = IERC20(_token0).balanceOf(address(this));\n        balance1 = IERC20(_token1).balanceOf(address(this));\n        }\n        uint amount0In = balance0 \u003e _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;\n        uint amount1In = balance1 \u003e _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;\n        require(amount0In \u003e 0 || amount1In \u003e 0, \u0027UniswapV2: INSUFFICIENT_INPUT_AMOUNT\u0027);\n        { // scope for reserve{0,1}Adjusted, avoids stack too deep errors\n        uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));\n        uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));\n        require(balance0Adjusted.mul(balance1Adjusted) \u003e= uint(_reserve0).mul(_reserve1).mul(1000**2), \u0027UniswapV2: K\u0027);\n        }\n\n        _update(balance0, balance1, _reserve0, _reserve1);\n        emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);\n    }\n\n    // force balances to match reserves\n    function skim(address to) external override lock {\n        address _token0 = token0; // gas savings\n        address _token1 = token1; // gas savings\n        _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));\n        _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));\n    }\n\n    // force reserves to match balances\n    function sync() external override lock {\n        _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);\n    }\n\n\n\n    // Migrated over from UniswapV2ERC20. Needed for ^0.6.0\n    // ===============================================\n\n    function _mint(address to, uint value) internal {\n        totalSupply = totalSupply.add(value);\n        balanceOf[to] = balanceOf[to].add(value);\n        emit Transfer(address(0), to, value);\n    }\n\n    function _burn(address from, uint value) internal {\n        balanceOf[from] = balanceOf[from].sub(value);\n        totalSupply = totalSupply.sub(value);\n        emit Transfer(from, address(0), value);\n    }\n\n    function _approve(address owner, address spender, uint value) private {\n        allowance[owner][spender] = value;\n        emit Approval(owner, spender, value);\n    }\n\n    function _transfer(address from, address to, uint value) private {\n        balanceOf[from] = balanceOf[from].sub(value);\n        balanceOf[to] = balanceOf[to].add(value);\n        emit Transfer(from, to, value);\n    }\n\n    function approve(address spender, uint value) external override returns (bool) {\n        _approve(msg.sender, spender, value);\n        return true;\n    }\n\n    function transfer(address to, uint value) external override returns (bool) {\n        _transfer(msg.sender, to, value);\n        return true;\n    }\n\n    function transferFrom(address from, address to, uint value) external override returns (bool) {\n        if (allowance[from][msg.sender] != uint(-1)) {\n            allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);\n        }\n        _transfer(from, to, value);\n        return true;\n    }\n\n    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {\n        require(deadline \u003e= block.timestamp, \u0027UniswapV2: EXPIRED\u0027);\n        bytes32 digest = keccak256(\n            abi.encodePacked(\n                \u0027\\x19\\x01\u0027,\n                DOMAIN_SEPARATOR,\n                keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))\n            )\n        );\n        address recoveredAddress = ecrecover(digest, v, r, s);\n        require(recoveredAddress != address(0) \u0026\u0026 recoveredAddress == owner, \u0027UniswapV2: INVALID_SIGNATURE\u0027);\n        _approve(owner, spender, value);\n    }\n\n\n\n}"},"UniswapV2Router02.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Factory.sol\u0027;\nimport \u0027./TransferHelper.sol\u0027;\n\nimport \u0027./IUniswapV2Router02.sol\u0027;\nimport \u0027./UniswapV2Library.sol\u0027;\nimport \u0027./SafeMath.sol\u0027;\nimport \u0027./IERC20.sol\u0027;\nimport \u0027./IWETH.sol\u0027;\n\ncontract UniswapV2Router02 is IUniswapV2Router02 {\n    using SafeMath for uint;\n\n    address public immutable override factory;\n    address public immutable override WETH;\n\n    modifier ensure(uint deadline) {\n        require(deadline \u003e= block.timestamp, \u0027UniswapV2Router: EXPIRED\u0027);\n        _;\n    }\n\n    constructor(address _factory, address _WETH) public {\n        factory = _factory;\n        WETH = _WETH;\n    }\n\n    receive() external payable {\n        assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract\n    }\n\n    // **** ADD LIQUIDITY ****\n    function _addLiquidity(\n        address tokenA,\n        address tokenB,\n        uint amountADesired,\n        uint amountBDesired,\n        uint amountAMin,\n        uint amountBMin\n    ) internal virtual returns (uint amountA, uint amountB) {\n        // create the pair if it doesn\u0027t exist yet\n        if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {\n            IUniswapV2Factory(factory).createPair(tokenA, tokenB);\n        }\n        (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);\n        if (reserveA == 0 \u0026\u0026 reserveB == 0) {\n            (amountA, amountB) = (amountADesired, amountBDesired);\n        } else {\n            uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);\n            if (amountBOptimal \u003c= amountBDesired) {\n                require(amountBOptimal \u003e= amountBMin, \u0027UniswapV2Router: INSUFFICIENT_B_AMOUNT\u0027);\n                (amountA, amountB) = (amountADesired, amountBOptimal);\n            } else {\n                uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);\n                assert(amountAOptimal \u003c= amountADesired);\n                require(amountAOptimal \u003e= amountAMin, \u0027UniswapV2Router: INSUFFICIENT_A_AMOUNT\u0027);\n                (amountA, amountB) = (amountAOptimal, amountBDesired);\n            }\n        }\n    }\n    function addLiquidity(\n        address tokenA,\n        address tokenB,\n        uint amountADesired,\n        uint amountBDesired,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {\n        (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);\n        address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n        TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);\n        TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);\n        liquidity = IUniswapV2Pair(pair).mint(to);\n    }\n    function addLiquidityETH(\n        address token,\n        uint amountTokenDesired,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {\n        (amountToken, amountETH) = _addLiquidity(\n            token,\n            WETH,\n            amountTokenDesired,\n            msg.value,\n            amountTokenMin,\n            amountETHMin\n        );\n        address pair = UniswapV2Library.pairFor(factory, token, WETH);\n        TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);\n        IWETH(WETH).deposit{value: amountETH}();\n        assert(IWETH(WETH).transfer(pair, amountETH));\n        liquidity = IUniswapV2Pair(pair).mint(to);\n        // refund dust eth, if any\n        if (msg.value \u003e amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);\n    }\n\n    // **** REMOVE LIQUIDITY ****\n    function removeLiquidity(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {\n        address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n        IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair\n        (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);\n        (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);\n        (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);\n        require(amountA \u003e= amountAMin, \u0027UniswapV2Router: INSUFFICIENT_A_AMOUNT\u0027);\n        require(amountB \u003e= amountBMin, \u0027UniswapV2Router: INSUFFICIENT_B_AMOUNT\u0027);\n    }\n    function removeLiquidityETH(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {\n        (amountToken, amountETH) = removeLiquidity(\n            token,\n            WETH,\n            liquidity,\n            amountTokenMin,\n            amountETHMin,\n            address(this),\n            deadline\n        );\n        TransferHelper.safeTransfer(token, to, amountToken);\n        IWETH(WETH).withdraw(amountETH);\n        TransferHelper.safeTransferETH(to, amountETH);\n    }\n    function removeLiquidityWithPermit(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external virtual override returns (uint amountA, uint amountB) {\n        address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n        uint value = approveMax ? uint(-1) : liquidity;\n        IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n        (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);\n    }\n    function removeLiquidityETHWithPermit(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external virtual override returns (uint amountToken, uint amountETH) {\n        address pair = UniswapV2Library.pairFor(factory, token, WETH);\n        uint value = approveMax ? uint(-1) : liquidity;\n        IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n        (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);\n    }\n\n    // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****\n    function removeLiquidityETHSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) public virtual override ensure(deadline) returns (uint amountETH) {\n        (, amountETH) = removeLiquidity(\n            token,\n            WETH,\n            liquidity,\n            amountTokenMin,\n            amountETHMin,\n            address(this),\n            deadline\n        );\n        TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));\n        IWETH(WETH).withdraw(amountETH);\n        TransferHelper.safeTransferETH(to, amountETH);\n    }\n    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external virtual override returns (uint amountETH) {\n        address pair = UniswapV2Library.pairFor(factory, token, WETH);\n        uint value = approveMax ? uint(-1) : liquidity;\n        IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n        amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(\n            token, liquidity, amountTokenMin, amountETHMin, to, deadline\n        );\n    }\n\n    // **** SWAP ****\n    // requires the initial amount to have already been sent to the first pair\n    function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {\n        for (uint i; i \u003c path.length - 1; i++) {\n            (address input, address output) = (path[i], path[i + 1]);\n            (address token0,) = UniswapV2Library.sortTokens(input, output);\n            uint amountOut = amounts[i + 1];\n            (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));\n            address to = i \u003c path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;\n            IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(\n                amount0Out, amount1Out, to, new bytes(0)\n            );\n        }\n    }\n    function swapExactTokensForTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) returns (uint[] memory amounts) {\n        amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);\n        require(amounts[amounts.length - 1] \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, to);\n    }\n    function swapTokensForExactTokens(\n        uint amountOut,\n        uint amountInMax,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) returns (uint[] memory amounts) {\n        amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n        require(amounts[0] \u003c= amountInMax, \u0027UniswapV2Router: EXCESSIVE_INPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, to);\n    }\n    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        payable\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[0] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);\n        require(amounts[amounts.length - 1] \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        IWETH(WETH).deposit{value: amounts[0]}();\n        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));\n        _swap(amounts, path, to);\n    }\n    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[path.length - 1] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n        require(amounts[0] \u003c= amountInMax, \u0027UniswapV2Router: EXCESSIVE_INPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, address(this));\n        IWETH(WETH).withdraw(amounts[amounts.length - 1]);\n        TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n    }\n    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[path.length - 1] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);\n        require(amounts[amounts.length - 1] \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, address(this));\n        IWETH(WETH).withdraw(amounts[amounts.length - 1]);\n        TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n    }\n    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        payable\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[0] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n        require(amounts[0] \u003c= msg.value, \u0027UniswapV2Router: EXCESSIVE_INPUT_AMOUNT\u0027);\n        IWETH(WETH).deposit{value: amounts[0]}();\n        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));\n        _swap(amounts, path, to);\n        // refund dust eth, if any\n        if (msg.value \u003e amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);\n    }\n\n    // **** SWAP (supporting fee-on-transfer tokens) ****\n    // requires the initial amount to have already been sent to the first pair\n    function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {\n        for (uint i; i \u003c path.length - 1; i++) {\n            (address input, address output) = (path[i], path[i + 1]);\n            (address token0,) = UniswapV2Library.sortTokens(input, output);\n            IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));\n            uint amountInput;\n            uint amountOutput;\n            { // scope to avoid stack too deep errors\n            (uint reserve0, uint reserve1,) = pair.getReserves();\n            (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);\n            amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);\n            amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);\n            }\n            (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));\n            address to = i \u003c path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;\n            pair.swap(amount0Out, amount1Out, to, new bytes(0));\n        }\n    }\n    function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) {\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn\n        );\n        uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);\n        _swapSupportingFeeOnTransferTokens(path, to);\n        require(\n            IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) \u003e= amountOutMin,\n            \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027\n        );\n    }\n    function swapExactETHForTokensSupportingFeeOnTransferTokens(\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    )\n        external\n        virtual\n        override\n        payable\n        ensure(deadline)\n    {\n        require(path[0] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        uint amountIn = msg.value;\n        IWETH(WETH).deposit{value: amountIn}();\n        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));\n        uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);\n        _swapSupportingFeeOnTransferTokens(path, to);\n        require(\n            IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) \u003e= amountOutMin,\n            \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027\n        );\n    }\n    function swapExactTokensForETHSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    )\n        external\n        virtual\n        override\n        ensure(deadline)\n    {\n        require(path[path.length - 1] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn\n        );\n        _swapSupportingFeeOnTransferTokens(path, address(this));\n        uint amountOut = IERC20(WETH).balanceOf(address(this));\n        require(amountOut \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        IWETH(WETH).withdraw(amountOut);\n        TransferHelper.safeTransferETH(to, amountOut);\n    }\n\n    // **** LIBRARY FUNCTIONS ****\n    function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {\n        return UniswapV2Library.quote(amountA, reserveA, reserveB);\n    }\n\n    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)\n        public\n        pure\n        virtual\n        override\n        returns (uint amountOut)\n    {\n        return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);\n    }\n\n    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)\n        public\n        pure\n        virtual\n        override\n        returns (uint amountIn)\n    {\n        return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);\n    }\n\n    function getAmountsOut(uint amountIn, address[] memory path)\n        public\n        view\n        virtual\n        override\n        returns (uint[] memory amounts)\n    {\n        return UniswapV2Library.getAmountsOut(factory, amountIn, path);\n    }\n\n    function getAmountsIn(uint amountOut, address[] memory path)\n        public\n        view\n        virtual\n        override\n        returns (uint[] memory amounts)\n    {\n        return UniswapV2Library.getAmountsIn(factory, amountOut, path);\n    }\n}"},"UniswapV2Router02_Modified.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Factory.sol\u0027;\nimport \u0027./TransferHelper.sol\u0027;\n\nimport \u0027./IUniswapV2Router02.sol\u0027;\nimport \u0027./UniswapV2Library.sol\u0027;\nimport \u0027./SafeMath.sol\u0027;\nimport \u0027./IERC20.sol\u0027;\nimport \u0027./IWETH.sol\u0027;\n\ncontract UniswapV2Router02_Modified is IUniswapV2Router02 {\n    using SafeMath for uint;\n\n    address public immutable override factory;\n    address public immutable override WETH;\n\n    modifier ensure(uint deadline) {\n        require(deadline \u003e= block.timestamp, \u0027UniswapV2Router: EXPIRED\u0027);\n        _;\n    }\n\n    constructor(address _factory, address _WETH) public {\n        factory = _factory;\n        WETH = _WETH;\n    }\n\n    receive() external payable {\n        assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract\n    }\n\n    // **** ADD LIQUIDITY ****\n    function _addLiquidity(\n        address tokenA,\n        address tokenB,\n        uint amountADesired,\n        uint amountBDesired,\n        uint amountAMin,\n        uint amountBMin\n    ) internal virtual returns (uint amountA, uint amountB) {\n        // create the pair if it doesn\u0027t exist yet\n        if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {\n            IUniswapV2Factory(factory).createPair(tokenA, tokenB);\n        }\n        (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);\n        if (reserveA == 0 \u0026\u0026 reserveB == 0) {\n            (amountA, amountB) = (amountADesired, amountBDesired);\n        } else {\n            uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);\n            if (amountBOptimal \u003c= amountBDesired) {\n                require(amountBOptimal \u003e= amountBMin, \u0027UniswapV2Router: INSUFFICIENT_B_AMOUNT\u0027);\n                (amountA, amountB) = (amountADesired, amountBOptimal);\n            } else {\n                uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);\n                assert(amountAOptimal \u003c= amountADesired);\n                require(amountAOptimal \u003e= amountAMin, \u0027UniswapV2Router: INSUFFICIENT_A_AMOUNT\u0027);\n                (amountA, amountB) = (amountAOptimal, amountBDesired);\n            }\n        }\n    }\n    function addLiquidity(\n        address tokenA,\n        address tokenB,\n        uint amountADesired,\n        uint amountBDesired,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {\n        (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);\n        address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n        TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);\n        TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);\n        liquidity = IUniswapV2Pair(pair).mint(to);\n    }\n    function addLiquidityETH(\n        address token,\n        uint amountTokenDesired,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {\n        (amountToken, amountETH) = _addLiquidity(\n            token,\n            WETH,\n            amountTokenDesired,\n            msg.value,\n            amountTokenMin,\n            amountETHMin\n        );\n        address pair = UniswapV2Library.pairFor(factory, token, WETH);\n        TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);\n        \n        \n        TransferHelper.safeTransferFrom(WETH, msg.sender, pair, amountETH);\n\n        // IWETH(WETH).transferFrom(msg.sender, pair, amountETH);\n        // IWETH(WETH).deposit{value: amountETH}();\n        // assert(IWETH(WETH).transfer(pair, amountETH));\n\n        // require(false, \"HELLO: HOW ARE YOU TODAY!\");\n\n        liquidity = IUniswapV2Pair(pair).mint(to); // \u003c\u003c PROBLEM IS HERE\n\n        // refund dust eth, if any\n        if (msg.value \u003e amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);\n    }\n\n    // **** REMOVE LIQUIDITY ****\n    function removeLiquidity(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {\n        address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n        IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair\n        (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);\n        (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);\n        (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);\n        require(amountA \u003e= amountAMin, \u0027UniswapV2Router: INSUFFICIENT_A_AMOUNT\u0027);\n        require(amountB \u003e= amountBMin, \u0027UniswapV2Router: INSUFFICIENT_B_AMOUNT\u0027);\n    }\n    function removeLiquidityETH(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {\n        (amountToken, amountETH) = removeLiquidity(\n            token,\n            WETH,\n            liquidity,\n            amountTokenMin,\n            amountETHMin,\n            address(this),\n            deadline\n        );\n        TransferHelper.safeTransfer(token, to, amountToken);\n        IWETH(WETH).withdraw(amountETH);\n        TransferHelper.safeTransferETH(to, amountETH);\n    }\n    function removeLiquidityWithPermit(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external virtual override returns (uint amountA, uint amountB) {\n        address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n        uint value = approveMax ? uint(-1) : liquidity;\n        IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n        (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);\n    }\n    function removeLiquidityETHWithPermit(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external virtual override returns (uint amountToken, uint amountETH) {\n        address pair = UniswapV2Library.pairFor(factory, token, WETH);\n        uint value = approveMax ? uint(-1) : liquidity;\n        IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n        (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);\n    }\n\n    // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****\n    function removeLiquidityETHSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) public virtual override ensure(deadline) returns (uint amountETH) {\n        (, amountETH) = removeLiquidity(\n            token,\n            WETH,\n            liquidity,\n            amountTokenMin,\n            amountETHMin,\n            address(this),\n            deadline\n        );\n        TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));\n        IWETH(WETH).withdraw(amountETH);\n        TransferHelper.safeTransferETH(to, amountETH);\n    }\n    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external virtual override returns (uint amountETH) {\n        address pair = UniswapV2Library.pairFor(factory, token, WETH);\n        uint value = approveMax ? uint(-1) : liquidity;\n        IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n        amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(\n            token, liquidity, amountTokenMin, amountETHMin, to, deadline\n        );\n    }\n\n    // **** SWAP ****\n    // requires the initial amount to have already been sent to the first pair\n    function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {\n        for (uint i; i \u003c path.length - 1; i++) {\n            (address input, address output) = (path[i], path[i + 1]);\n            (address token0,) = UniswapV2Library.sortTokens(input, output);\n            uint amountOut = amounts[i + 1];\n            (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));\n            address to = i \u003c path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;\n            IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(\n                amount0Out, amount1Out, to, new bytes(0)\n            );\n        }\n    }\n    function swapExactTokensForTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) returns (uint[] memory amounts) {\n        amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);\n        require(amounts[amounts.length - 1] \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, to);\n    }\n    function swapTokensForExactTokens(\n        uint amountOut,\n        uint amountInMax,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) returns (uint[] memory amounts) {\n        amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n        require(amounts[0] \u003c= amountInMax, \u0027UniswapV2Router: EXCESSIVE_INPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, to);\n    }\n    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        payable\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[0] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);\n        require(amounts[amounts.length - 1] \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        IWETH(WETH).deposit{value: amounts[0]}();\n        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));\n        _swap(amounts, path, to);\n    }\n    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[path.length - 1] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n        require(amounts[0] \u003c= amountInMax, \u0027UniswapV2Router: EXCESSIVE_INPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, address(this));\n        IWETH(WETH).withdraw(amounts[amounts.length - 1]);\n        TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n    }\n    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[path.length - 1] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);\n        require(amounts[amounts.length - 1] \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, address(this));\n        IWETH(WETH).withdraw(amounts[amounts.length - 1]);\n        TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n    }\n    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        payable\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[0] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n        require(amounts[0] \u003c= msg.value, \u0027UniswapV2Router: EXCESSIVE_INPUT_AMOUNT\u0027);\n        IWETH(WETH).deposit{value: amounts[0]}();\n        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));\n        _swap(amounts, path, to);\n        // refund dust eth, if any\n        if (msg.value \u003e amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);\n    }\n\n    // **** SWAP (supporting fee-on-transfer tokens) ****\n    // requires the initial amount to have already been sent to the first pair\n    function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {\n        // for (uint i; i \u003c path.length - 1; i++) {\n        //     (address input, address output) = (path[i], path[i + 1]);\n        //     (address token0,) = UniswapV2Library.sortTokens(input, output);\n        //     IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));\n        //     uint amountInput;\n        //     uint amountOutput;\n        //     { // scope to avoid stack too deep errors\n        //     (uint reserve0, uint reserve1,) = pair.getReserves();\n        //     (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);\n        //     amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);\n        //     amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);\n        //     }\n        //     (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));\n        //     address to = i \u003c path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;\n        //     pair.swap(amount0Out, amount1Out, to, new bytes(0));\n        // }\n    }\n    function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) {\n        // TransferHelper.safeTransferFrom(\n        //     path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn\n        // );\n        // uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);\n        // _swapSupportingFeeOnTransferTokens(path, to);\n        // require(\n        //     IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) \u003e= amountOutMin,\n        //     \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027\n        // );\n    }\n    function swapExactETHForTokensSupportingFeeOnTransferTokens(\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    )\n        external\n        virtual\n        override\n        payable\n        ensure(deadline)\n    {\n        // require(path[0] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        // uint amountIn = msg.value;\n        // IWETH(WETH).deposit{value: amountIn}();\n        // assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));\n        // uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);\n        // _swapSupportingFeeOnTransferTokens(path, to);\n        // require(\n        //     IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) \u003e= amountOutMin,\n        //     \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027\n        // );\n    }\n    function swapExactTokensForETHSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    )\n        external\n        virtual\n        override\n        ensure(deadline)\n    {\n        // require(path[path.length - 1] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        // TransferHelper.safeTransferFrom(\n        //     path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn\n        // );\n        // _swapSupportingFeeOnTransferTokens(path, address(this));\n        // uint amountOut = IERC20(WETH).balanceOf(address(this));\n        // require(amountOut \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        // IWETH(WETH).withdraw(amountOut);\n        // TransferHelper.safeTransferETH(to, amountOut);\n    }\n\n    // **** LIBRARY FUNCTIONS ****\n    function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {\n        return UniswapV2Library.quote(amountA, reserveA, reserveB);\n    }\n\n    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)\n        public\n        pure\n        virtual\n        override\n        returns (uint amountOut)\n    {\n        return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);\n    }\n\n    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)\n        public\n        pure\n        virtual\n        override\n        returns (uint amountIn)\n    {\n        return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);\n    }\n\n    function getAmountsOut(uint amountIn, address[] memory path)\n        public\n        view\n        virtual\n        override\n        returns (uint[] memory amounts)\n    {\n        return UniswapV2Library.getAmountsOut(factory, amountIn, path);\n    }\n\n    function getAmountsIn(uint amountOut, address[] memory path)\n        public\n        view\n        virtual\n        override\n        returns (uint[] memory amounts)\n    {\n        return UniswapV2Library.getAmountsIn(factory, amountOut, path);\n    }\n}"},"UQ112x112.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))\n\n// range: [0, 2**112 - 1]\n// resolution: 1 / 2**112\n\nlibrary UQ112x112 {\n    uint224 constant Q112 = 2**112;\n\n    // encode a uint112 as a UQ112x112\n    function encode(uint112 y) internal pure returns (uint224 z) {\n        z = uint224(y) * Q112; // never overflows\n    }\n\n    // divide a UQ112x112 by a uint112, returning a UQ112x112\n    function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {\n        z = x / uint224(y);\n    }\n}"},"WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IWETH.sol\u0027;\n\n// Copyright (C) 2015, 2016, 2017 Dapphub\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see \u003chttp://www.gnu.org/licenses/\u003e.\n\ncontract WETH is IWETH {\n    string public name     = \"Wrapped Ether\";\n    string public symbol   = \"WETH\";\n    uint8  public decimals = 18;\n\n    event  Approval(address indexed src, address indexed guy, uint wad);\n    event  Transfer(address indexed src, address indexed dst, uint wad);\n    event  Deposit(address indexed dst, uint wad);\n    event  Withdrawal(address indexed src, uint wad);\n\n    mapping (address =\u003e uint)                       public  balanceOf;\n    mapping (address =\u003e mapping (address =\u003e uint))  public  allowance;\n\n    fallback() external payable {\n        deposit();\n    }\n\n    receive() external payable { }\n\n    constructor (address _creator_address ) public \n    {\n        balanceOf[_creator_address] = 1000000e18; // this is for testing only\n    }\n\n\n    function deposit() public override payable {\n        balanceOf[msg.sender] += msg.value;\n        emit Deposit(msg.sender, msg.value);\n    }\n    function withdraw(uint wad) override public {\n        require(balanceOf[msg.sender] \u003e= wad);\n        balanceOf[msg.sender] -= wad;\n        msg.sender.transfer(wad);\n        emit Withdrawal(msg.sender, wad);\n    }\n\n    function totalSupply() public view returns (uint) {\n        return address(this).balance;\n    }\n\n    function approve(address guy, uint wad) public returns (bool) {\n        allowance[msg.sender][guy] = wad;\n        emit Approval(msg.sender, guy, wad);\n        return true;\n    }\n\n    function transfer(address dst, uint wad) public override returns (bool) {\n        return transferFrom(msg.sender, dst, wad);\n    }\n\n    function transferFrom(address src, address dst, uint wad)\n        public\n        override\n        returns (bool)\n    {\n        require(balanceOf[src] \u003e= wad);\n\n        if (src != msg.sender \u0026\u0026 allowance[src][msg.sender] != uint(-1)) {\n            require(allowance[src][msg.sender] \u003e= wad);\n            allowance[src][msg.sender] -= wad;\n        }\n\n        balanceOf[src] -= wad;\n        balanceOf[dst] += wad;\n\n        emit Transfer(src, dst, wad);\n\n        return true;\n    }\n}\n\n\n/*\n                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. \u003chttp://fsf.org/\u003e\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers\u0027 and authors\u0027 protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users\u0027 and\nauthors\u0027 sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users\u0027 freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work\u0027s\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users\u0027 Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work\u0027s\nusers, your or third parties\u0027 legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program\u0027s source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation\u0027s users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party\u0027s predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor\u0027s \"contributor version\".\n\n  A contributor\u0027s \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor\u0027s essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient\u0027s use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others\u0027 Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy\u0027s\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    \u003cone line to give the program\u0027s name and a brief idea of what it does.\u003e\n    Copyright (C) \u003cyear\u003e  \u003cname of author\u003e\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see \u003chttp://www.gnu.org/licenses/\u003e.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    \u003cprogram\u003e  Copyright (C) \u003cyear\u003e  \u003cname of author\u003e\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w\u0027.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c\u0027 for details.\n\nThe hypothetical commands `show w\u0027 and `show c\u0027 should show the appropriate\nparts of the General Public License.  Of course, your program\u0027s commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n\u003chttp://www.gnu.org/licenses/\u003e.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n\u003chttp://www.gnu.org/philosophy/why-not-lgpl.html\u003e.\n\n*/"}}

                File 3 of 5: Settlement
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                pragma abicoder v1;
                /**
                 * @title Interface for interactor which acts after `taker -> maker` transfers.
                 * @notice The order filling steps are `preInteraction` =>` Transfer "maker -> taker"` => **`Interaction`** => `Transfer "taker -> maker"` => `postInteraction`
                 */
                interface IInteractionNotificationReceiver {
                    /**
                     * @notice Callback method that gets called after all funds transfers
                     * @param taker Taker address (tx sender)
                     * @param makingAmount Actual making amount
                     * @param takingAmount Actual taking amount
                     * @param interactionData Interaction calldata
                     * @return offeredTakingAmount Suggested amount. Order is filled with this amount if maker or taker getter functions are not defined.
                     */
                    function fillOrderInteraction(
                        address taker,
                        uint256 makingAmount,
                        uint256 takingAmount,
                        bytes memory interactionData
                    ) external returns(uint256 offeredTakingAmount);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import "../OrderLib.sol";
                interface IOrderMixin {
                    /**
                     * @notice Returns unfilled amount for order. Throws if order does not exist
                     * @param orderHash Order's hash. Can be obtained by the `hashOrder` function
                     * @return amount Unfilled amount
                     */
                    function remaining(bytes32 orderHash) external view returns(uint256 amount);
                    /**
                     * @notice Returns unfilled amount for order
                     * @param orderHash Order's hash. Can be obtained by the `hashOrder` function
                     * @return rawAmount Unfilled amount of order plus one if order exists. Otherwise 0
                     */
                    function remainingRaw(bytes32 orderHash) external view returns(uint256 rawAmount);
                    /**
                     * @notice Same as `remainingRaw` but for multiple orders
                     * @param orderHashes Array of hashes
                     * @return rawAmounts Array of amounts for each order plus one if order exists or 0 otherwise
                     */
                    function remainingsRaw(bytes32[] memory orderHashes) external view returns(uint256[] memory rawAmounts);
                    /**
                     * @notice Checks order predicate
                     * @param order Order to check predicate for
                     * @return result Predicate evaluation result. True if predicate allows to fill the order, false otherwise
                     */
                    function checkPredicate(OrderLib.Order calldata order) external view returns(bool result);
                    /**
                     * @notice Returns order hash according to EIP712 standard
                     * @param order Order to get hash for
                     * @return orderHash Hash of the order
                     */
                    function hashOrder(OrderLib.Order calldata order) external view returns(bytes32 orderHash);
                    /**
                     * @notice Delegates execution to custom implementation. Could be used to validate if `transferFrom` works properly
                     * @dev The function always reverts and returns the simulation results in revert data.
                     * @param target Addresses that will be delegated
                     * @param data Data that will be passed to delegatee
                     */
                    function simulate(address target, bytes calldata data) external;
                    /**
                     * @notice Cancels order.
                     * @dev Order is cancelled by setting remaining amount to _ORDER_FILLED value
                     * @param order Order quote to cancel
                     * @return orderRemaining Unfilled amount of order before cancellation
                     * @return orderHash Hash of the filled order
                     */
                    function cancelOrder(OrderLib.Order calldata order) external returns(uint256 orderRemaining, bytes32 orderHash);
                    /**
                     * @notice Fills an order. If one doesn't exist (first fill) it will be created using order.makerAssetData
                     * @param order Order quote to fill
                     * @param signature Signature to confirm quote ownership
                     * @param interaction A call data for InteractiveNotificationReceiver. Taker may execute interaction after getting maker assets and before sending taker assets.
                     * @param makingAmount Making amount
                     * @param takingAmount Taking amount
                     * @param skipPermitAndThresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount. Top-most bit specifies whether taker wants to skip maker's permit.
                     * @return actualMakingAmount Actual amount transferred from maker to taker
                     * @return actualTakingAmount Actual amount transferred from taker to maker
                     * @return orderHash Hash of the filled order
                     */
                    function fillOrder(
                        OrderLib.Order calldata order,
                        bytes calldata signature,
                        bytes calldata interaction,
                        uint256 makingAmount,
                        uint256 takingAmount,
                        uint256 skipPermitAndThresholdAmount
                    ) external payable returns(uint256 actualMakingAmount, uint256 actualTakingAmount, bytes32 orderHash);
                    /**
                     * @notice Same as `fillOrderTo` but calls permit first,
                     * allowing to approve token spending and make a swap in one transaction.
                     * Also allows to specify funds destination instead of `msg.sender`
                     * @dev See tests for examples
                     * @param order Order quote to fill
                     * @param signature Signature to confirm quote ownership
                     * @param interaction A call data for InteractiveNotificationReceiver. Taker may execute interaction after getting maker assets and before sending taker assets.
                     * @param makingAmount Making amount
                     * @param takingAmount Taking amount
                     * @param skipPermitAndThresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount. Top-most bit specifies whether taker wants to skip maker's permit.
                     * @param target Address that will receive swap funds
                     * @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call.
                     * @return actualMakingAmount Actual amount transferred from maker to taker
                     * @return actualTakingAmount Actual amount transferred from taker to maker
                     * @return orderHash Hash of the filled order
                     */
                    function fillOrderToWithPermit(
                        OrderLib.Order calldata order,
                        bytes calldata signature,
                        bytes calldata interaction,
                        uint256 makingAmount,
                        uint256 takingAmount,
                        uint256 skipPermitAndThresholdAmount,
                        address target,
                        bytes calldata permit
                    ) external returns(uint256 actualMakingAmount, uint256 actualTakingAmount, bytes32 orderHash);
                    /**
                     * @notice Same as `fillOrder` but allows to specify funds destination instead of `msg.sender`
                     * @param order_ Order quote to fill
                     * @param signature Signature to confirm quote ownership
                     * @param interaction A call data for InteractiveNotificationReceiver. Taker may execute interaction after getting maker assets and before sending taker assets.
                     * @param makingAmount Making amount
                     * @param takingAmount Taking amount
                     * @param skipPermitAndThresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount. Top-most bit specifies whether taker wants to skip maker's permit.
                     * @param target Address that will receive swap funds
                     * @return actualMakingAmount Actual amount transferred from maker to taker
                     * @return actualTakingAmount Actual amount transferred from taker to maker
                     * @return orderHash Hash of the filled order
                     */
                    function fillOrderTo(
                        OrderLib.Order calldata order_,
                        bytes calldata signature,
                        bytes calldata interaction,
                        uint256 makingAmount,
                        uint256 takingAmount,
                        uint256 skipPermitAndThresholdAmount,
                        address target
                    ) external payable returns(uint256 actualMakingAmount, uint256 actualTakingAmount, bytes32 orderHash);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import "@1inch/solidity-utils/contracts/libraries/ECDSA.sol";
                library OrderLib {
                    struct Order {
                        uint256 salt;
                        address makerAsset;
                        address takerAsset;
                        address maker;
                        address receiver;
                        address allowedSender;  // equals to Zero address on public orders
                        uint256 makingAmount;
                        uint256 takingAmount;
                        uint256 offsets;
                        // bytes makerAssetData;
                        // bytes takerAssetData;
                        // bytes getMakingAmount; // this.staticcall(abi.encodePacked(bytes, swapTakerAmount)) => (swapMakerAmount)
                        // bytes getTakingAmount; // this.staticcall(abi.encodePacked(bytes, swapMakerAmount)) => (swapTakerAmount)
                        // bytes predicate;       // this.staticcall(bytes) => (bool)
                        // bytes permit;          // On first fill: permit.1.call(abi.encodePacked(permit.selector, permit.2))
                        // bytes preInteraction;
                        // bytes postInteraction;
                        bytes interactions; // concat(makerAssetData, takerAssetData, getMakingAmount, getTakingAmount, predicate, permit, preIntercation, postInteraction)
                    }
                    bytes32 constant internal _LIMIT_ORDER_TYPEHASH = keccak256(
                        "Order("
                            "uint256 salt,"
                            "address makerAsset,"
                            "address takerAsset,"
                            "address maker,"
                            "address receiver,"
                            "address allowedSender,"
                            "uint256 makingAmount,"
                            "uint256 takingAmount,"
                            "uint256 offsets,"
                            "bytes interactions"
                        ")"
                    );
                    enum DynamicField {
                        MakerAssetData,
                        TakerAssetData,
                        GetMakingAmount,
                        GetTakingAmount,
                        Predicate,
                        Permit,
                        PreInteraction,
                        PostInteraction
                    }
                    function getterIsFrozen(bytes calldata getter) internal pure returns(bool) {
                        return getter.length == 1 && getter[0] == "x";
                    }
                    function _get(Order calldata order, DynamicField field) private pure returns(bytes calldata) {
                        uint256 bitShift = uint256(field) << 5; // field * 32
                        return order.interactions[
                            uint32((order.offsets << 32) >> bitShift):
                            uint32(order.offsets >> bitShift)
                        ];
                    }
                    function makerAssetData(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.MakerAssetData);
                    }
                    function takerAssetData(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.TakerAssetData);
                    }
                    function getMakingAmount(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.GetMakingAmount);
                    }
                    function getTakingAmount(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.GetTakingAmount);
                    }
                    function predicate(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.Predicate);
                    }
                    function permit(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.Permit);
                    }
                    function preInteraction(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.PreInteraction);
                    }
                    function postInteraction(Order calldata order) internal pure returns(bytes calldata) {
                        return _get(order, DynamicField.PostInteraction);
                    }
                    function hash(Order calldata order, bytes32 domainSeparator) internal pure returns(bytes32 result) {
                        bytes calldata interactions = order.interactions;
                        bytes32 typehash = _LIMIT_ORDER_TYPEHASH;
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                            // keccak256(abi.encode(_LIMIT_ORDER_TYPEHASH, orderWithoutInteractions, keccak256(order.interactions)));
                            calldatacopy(ptr, interactions.offset, interactions.length)
                            mstore(add(ptr, 0x140), keccak256(ptr, interactions.length))
                            calldatacopy(add(ptr, 0x20), order, 0x120)
                            mstore(ptr, typehash)
                            result := keccak256(ptr, 0x160)
                        }
                        result = ECDSA.toTypedDataHash(domainSeparator, result);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                pragma abicoder v1;
                interface IDaiLikePermit {
                    function permit(
                        address holder,
                        address spender,
                        uint256 nonce,
                        uint256 expiry,
                        bool allowed,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                pragma abicoder v1;
                import "@openzeppelin/contracts/interfaces/IERC1271.sol";
                library ECDSA {
                    // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                    // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                    // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
                    // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                    //
                    // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                    // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                    // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                    // these malleable signatures as well.
                    uint256 private constant _S_BOUNDARY = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 + 1;
                    uint256 private constant _COMPACT_S_MASK = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
                    uint256 private constant _COMPACT_V_SHIFT = 255;
                    function recover(
                        bytes32 hash,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal view returns (address signer) {
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            if lt(s, _S_BOUNDARY) {
                                let ptr := mload(0x40)
                                mstore(ptr, hash)
                                mstore(add(ptr, 0x20), v)
                                mstore(add(ptr, 0x40), r)
                                mstore(add(ptr, 0x60), s)
                                mstore(0, 0)
                                pop(staticcall(gas(), 0x1, ptr, 0x80, 0, 0x20))
                                signer := mload(0)
                            }
                        }
                    }
                    function recover(
                        bytes32 hash,
                        bytes32 r,
                        bytes32 vs
                    ) internal view returns (address signer) {
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let s := and(vs, _COMPACT_S_MASK)
                            if lt(s, _S_BOUNDARY) {
                                let ptr := mload(0x40)
                                mstore(ptr, hash)
                                mstore(add(ptr, 0x20), add(27, shr(_COMPACT_V_SHIFT, vs)))
                                mstore(add(ptr, 0x40), r)
                                mstore(add(ptr, 0x60), s)
                                mstore(0, 0)
                                pop(staticcall(gas(), 0x1, ptr, 0x80, 0, 0x20))
                                signer := mload(0)
                            }
                        }
                    }
                    /// @dev WARNING!!!
                    /// There is a known signature malleability issue with two representations of signatures!
                    /// Even though this function is able to verify both standard 65-byte and compact 64-byte EIP-2098 signatures
                    /// one should never use raw signatures for any kind of invalidation logic in their code.
                    /// As the standard and compact representations are interchangeable any invalidation logic that relies on
                    /// signature uniqueness will get rekt.
                    /// More info: https://github.com/OpenZeppelin/openzeppelin-contracts/security/advisories/GHSA-4h98-2769-gh6h
                    function recover(bytes32 hash, bytes calldata signature) internal view returns (address signer) {
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                            // memory[ptr:ptr+0x80] = (hash, v, r, s)
                            switch signature.length
                            case 65 {
                                // memory[ptr+0x20:ptr+0x80] = (v, r, s)
                                mstore(add(ptr, 0x20), byte(0, calldataload(add(signature.offset, 0x40))))
                                calldatacopy(add(ptr, 0x40), signature.offset, 0x40)
                            }
                            case 64 {
                                // memory[ptr+0x20:ptr+0x80] = (v, r, s)
                                let vs := calldataload(add(signature.offset, 0x20))
                                mstore(add(ptr, 0x20), add(27, shr(_COMPACT_V_SHIFT, vs)))
                                calldatacopy(add(ptr, 0x40), signature.offset, 0x20)
                                mstore(add(ptr, 0x60), and(vs, _COMPACT_S_MASK))
                            }
                            default {
                                ptr := 0
                            }
                            if ptr {
                                if lt(mload(add(ptr, 0x60)), _S_BOUNDARY) {
                                    // memory[ptr:ptr+0x20] = (hash)
                                    mstore(ptr, hash)
                                    mstore(0, 0)
                                    pop(staticcall(gas(), 0x1, ptr, 0x80, 0, 0x20))
                                    signer := mload(0)
                                }
                            }
                        }
                    }
                    function recoverOrIsValidSignature(
                        address signer,
                        bytes32 hash,
                        bytes calldata signature
                    ) internal view returns (bool success) {
                        if (signer == address(0)) return false;
                        if ((signature.length == 64 || signature.length == 65) && recover(hash, signature) == signer) {
                            return true;
                        }
                        return isValidSignature(signer, hash, signature);
                    }
                    function recoverOrIsValidSignature(
                        address signer,
                        bytes32 hash,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal view returns (bool success) {
                        if (signer == address(0)) return false;
                        if (recover(hash, v, r, s) == signer) {
                            return true;
                        }
                        return isValidSignature(signer, hash, v, r, s);
                    }
                    function recoverOrIsValidSignature(
                        address signer,
                        bytes32 hash,
                        bytes32 r,
                        bytes32 vs
                    ) internal view returns (bool success) {
                        if (signer == address(0)) return false;
                        if (recover(hash, r, vs) == signer) {
                            return true;
                        }
                        return isValidSignature(signer, hash, r, vs);
                    }
                    function recoverOrIsValidSignature65(
                        address signer,
                        bytes32 hash,
                        bytes32 r,
                        bytes32 vs
                    ) internal view returns (bool success) {
                        if (signer == address(0)) return false;
                        if (recover(hash, r, vs) == signer) {
                            return true;
                        }
                        return isValidSignature65(signer, hash, r, vs);
                    }
                    function isValidSignature(
                        address signer,
                        bytes32 hash,
                        bytes calldata signature
                    ) internal view returns (bool success) {
                        // (bool success, bytes memory data) = signer.staticcall(abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature));
                        // return success && data.length >= 4 && abi.decode(data, (bytes4)) == IERC1271.isValidSignature.selector;
                        bytes4 selector = IERC1271.isValidSignature.selector;
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                            mstore(ptr, selector)
                            mstore(add(ptr, 0x04), hash)
                            mstore(add(ptr, 0x24), 0x40)
                            mstore(add(ptr, 0x44), signature.length)
                            calldatacopy(add(ptr, 0x64), signature.offset, signature.length)
                            if staticcall(gas(), signer, ptr, add(0x64, signature.length), 0, 0x20) {
                                success := and(eq(selector, mload(0)), eq(returndatasize(), 0x20))
                            }
                        }
                    }
                    function isValidSignature(
                        address signer,
                        bytes32 hash,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal view returns (bool success) {
                        bytes4 selector = IERC1271.isValidSignature.selector;
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                            mstore(ptr, selector)
                            mstore(add(ptr, 0x04), hash)
                            mstore(add(ptr, 0x24), 0x40)
                            mstore(add(ptr, 0x44), 65)
                            mstore(add(ptr, 0x64), r)
                            mstore(add(ptr, 0x84), s)
                            mstore8(add(ptr, 0xa4), v)
                            if staticcall(gas(), signer, ptr, 0xa5, 0, 0x20) {
                                success := and(eq(selector, mload(0)), eq(returndatasize(), 0x20))
                            }
                        }
                    }
                    function isValidSignature(
                        address signer,
                        bytes32 hash,
                        bytes32 r,
                        bytes32 vs
                    ) internal view returns (bool success) {
                        // (bool success, bytes memory data) = signer.staticcall(abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, abi.encodePacked(r, vs)));
                        // return success && data.length >= 4 && abi.decode(data, (bytes4)) == IERC1271.isValidSignature.selector;
                        bytes4 selector = IERC1271.isValidSignature.selector;
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                            mstore(ptr, selector)
                            mstore(add(ptr, 0x04), hash)
                            mstore(add(ptr, 0x24), 0x40)
                            mstore(add(ptr, 0x44), 64)
                            mstore(add(ptr, 0x64), r)
                            mstore(add(ptr, 0x84), vs)
                            if staticcall(gas(), signer, ptr, 0xa4, 0, 0x20) {
                                success := and(eq(selector, mload(0)), eq(returndatasize(), 0x20))
                            }
                        }
                    }
                    function isValidSignature65(
                        address signer,
                        bytes32 hash,
                        bytes32 r,
                        bytes32 vs
                    ) internal view returns (bool success) {
                        // (bool success, bytes memory data) = signer.staticcall(abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, abi.encodePacked(r, vs & ~uint256(1 << 255), uint8(vs >> 255))));
                        // return success && data.length >= 4 && abi.decode(data, (bytes4)) == IERC1271.isValidSignature.selector;
                        bytes4 selector = IERC1271.isValidSignature.selector;
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                            mstore(ptr, selector)
                            mstore(add(ptr, 0x04), hash)
                            mstore(add(ptr, 0x24), 0x40)
                            mstore(add(ptr, 0x44), 65)
                            mstore(add(ptr, 0x64), r)
                            mstore(add(ptr, 0x84), and(vs, _COMPACT_S_MASK))
                            mstore8(add(ptr, 0xa4), add(27, shr(_COMPACT_V_SHIFT, vs)))
                            if staticcall(gas(), signer, ptr, 0xa5, 0, 0x20) {
                                success := and(eq(selector, mload(0)), eq(returndatasize(), 0x20))
                            }
                        }
                    }
                    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 res) {
                        // 32 is the length in bytes of hash, enforced by the type signature above
                        // return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
                32", hash));
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            mstore(0, 0x19457468657265756d205369676e6564204d6573736167653a0a333200000000) // "\\x19Ethereum Signed Message:\
                32"
                            mstore(28, hash)
                            res := keccak256(0, 60)
                        }
                    }
                    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 res) {
                        // return keccak256(abi.encodePacked("\\x19\\x01", domainSeparator, structHash));
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                            mstore(ptr, 0x1901000000000000000000000000000000000000000000000000000000000000) // "\\x19\\x01"
                            mstore(add(ptr, 0x02), domainSeparator)
                            mstore(add(ptr, 0x22), structHash)
                            res := keccak256(ptr, 66)
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                pragma abicoder v1;
                /// @title Revert reason forwarder.
                library RevertReasonForwarder {
                    /// @dev Forwards latest externall call revert.
                    function reRevert() internal pure {
                        // bubble up revert reason from latest external call
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let ptr := mload(0x40)
                            returndatacopy(ptr, 0, returndatasize())
                            revert(ptr, returndatasize())
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                pragma abicoder v1;
                import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
                import "../interfaces/IDaiLikePermit.sol";
                import "../libraries/RevertReasonForwarder.sol";
                /// @title Implements efficient safe methods for ERC20 interface.
                library SafeERC20 {
                    error SafeTransferFailed();
                    error SafeTransferFromFailed();
                    error ForceApproveFailed();
                    error SafeIncreaseAllowanceFailed();
                    error SafeDecreaseAllowanceFailed();
                    error SafePermitBadLength();
                    /// @dev Ensures method do not revert or return boolean `true`, admits call to non-smart-contract.
                    function safeTransferFrom(
                        IERC20 token,
                        address from,
                        address to,
                        uint256 amount
                    ) internal {
                        bytes4 selector = token.transferFrom.selector;
                        bool success;
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let data := mload(0x40)
                            mstore(data, selector)
                            mstore(add(data, 0x04), from)
                            mstore(add(data, 0x24), to)
                            mstore(add(data, 0x44), amount)
                            success := call(gas(), token, 0, data, 100, 0x0, 0x20)
                            if success {
                                switch returndatasize()
                                case 0 {
                                    success := gt(extcodesize(token), 0)
                                }
                                default {
                                    success := and(gt(returndatasize(), 31), eq(mload(0), 1))
                                }
                            }
                        }
                        if (!success) revert SafeTransferFromFailed();
                    }
                    /// @dev Ensures method do not revert or return boolean `true`, admits call to non-smart-contract.
                    function safeTransfer(
                        IERC20 token,
                        address to,
                        uint256 value
                    ) internal {
                        if (!_makeCall(token, token.transfer.selector, to, value)) {
                            revert SafeTransferFailed();
                        }
                    }
                    /// @dev If `approve(from, to, amount)` fails, try to `approve(from, to, 0)` before retry.
                    function forceApprove(
                        IERC20 token,
                        address spender,
                        uint256 value
                    ) internal {
                        if (!_makeCall(token, token.approve.selector, spender, value)) {
                            if (
                                !_makeCall(token, token.approve.selector, spender, 0) ||
                                !_makeCall(token, token.approve.selector, spender, value)
                            ) {
                                revert ForceApproveFailed();
                            }
                        }
                    }
                    /// @dev Allowance increase with safe math check.
                    function safeIncreaseAllowance(
                        IERC20 token,
                        address spender,
                        uint256 value
                    ) internal {
                        uint256 allowance = token.allowance(address(this), spender);
                        if (value > type(uint256).max - allowance) revert SafeIncreaseAllowanceFailed();
                        forceApprove(token, spender, allowance + value);
                    }
                    /// @dev Allowance decrease with safe math check.
                    function safeDecreaseAllowance(
                        IERC20 token,
                        address spender,
                        uint256 value
                    ) internal {
                        uint256 allowance = token.allowance(address(this), spender);
                        if (value > allowance) revert SafeDecreaseAllowanceFailed();
                        forceApprove(token, spender, allowance - value);
                    }
                    /// @dev Calls either ERC20 or Dai `permit` for `token`, if unsuccessful forwards revert from external call.
                    function safePermit(IERC20 token, bytes calldata permit) internal {
                        if (!tryPermit(token, permit)) RevertReasonForwarder.reRevert();
                    }
                    function tryPermit(IERC20 token, bytes calldata permit) internal returns(bool) {
                        if (permit.length == 32 * 7) {
                            return _makeCalldataCall(token, IERC20Permit.permit.selector, permit);
                        }
                        if (permit.length == 32 * 8) {
                            return _makeCalldataCall(token, IDaiLikePermit.permit.selector, permit);
                        }
                        revert SafePermitBadLength();
                    }
                    function _makeCall(
                        IERC20 token,
                        bytes4 selector,
                        address to,
                        uint256 amount
                    ) private returns (bool success) {
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let data := mload(0x40)
                            mstore(data, selector)
                            mstore(add(data, 0x04), to)
                            mstore(add(data, 0x24), amount)
                            success := call(gas(), token, 0, data, 0x44, 0x0, 0x20)
                            if success {
                                switch returndatasize()
                                case 0 {
                                    success := gt(extcodesize(token), 0)
                                }
                                default {
                                    success := and(gt(returndatasize(), 31), eq(mload(0), 1))
                                }
                            }
                        }
                    }
                    function _makeCalldataCall(
                        IERC20 token,
                        bytes4 selector,
                        bytes calldata args
                    ) private returns (bool success) {
                        /// @solidity memory-safe-assembly
                        assembly { // solhint-disable-line no-inline-assembly
                            let len := add(4, args.length)
                            let data := mload(0x40)
                            mstore(data, selector)
                            calldatacopy(add(data, 0x04), args.offset, args.length)
                            success := call(gas(), token, 0, data, len, 0x0, 0x20)
                            if success {
                                switch returndatasize()
                                case 0 {
                                    success := gt(extcodesize(token), 0)
                                }
                                default {
                                    success := and(gt(returndatasize(), 31), eq(mload(0), 1))
                                }
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
                pragma solidity ^0.8.0;
                import "../utils/Context.sol";
                /**
                 * @dev Contract module which provides a basic access control mechanism, where
                 * there is an account (an owner) that can be granted exclusive access to
                 * specific functions.
                 *
                 * By default, the owner account will be the one that deploys the contract. This
                 * can later be changed with {transferOwnership}.
                 *
                 * This module is used through inheritance. It will make available the modifier
                 * `onlyOwner`, which can be applied to your functions to restrict their use to
                 * the owner.
                 */
                abstract contract Ownable is Context {
                    address private _owner;
                    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                    /**
                     * @dev Initializes the contract setting the deployer as the initial owner.
                     */
                    constructor() {
                        _transferOwnership(_msgSender());
                    }
                    /**
                     * @dev Throws if called by any account other than the owner.
                     */
                    modifier onlyOwner() {
                        _checkOwner();
                        _;
                    }
                    /**
                     * @dev Returns the address of the current owner.
                     */
                    function owner() public view virtual returns (address) {
                        return _owner;
                    }
                    /**
                     * @dev Throws if the sender is not the owner.
                     */
                    function _checkOwner() internal view virtual {
                        require(owner() == _msgSender(), "Ownable: caller is not the owner");
                    }
                    /**
                     * @dev Leaves the contract without owner. It will not be possible to call
                     * `onlyOwner` functions anymore. Can only be called by the current owner.
                     *
                     * NOTE: Renouncing ownership will leave the contract without an owner,
                     * thereby removing any functionality that is only available to the owner.
                     */
                    function renounceOwnership() public virtual onlyOwner {
                        _transferOwnership(address(0));
                    }
                    /**
                     * @dev Transfers ownership of the contract to a new account (`newOwner`).
                     * Can only be called by the current owner.
                     */
                    function transferOwnership(address newOwner) public virtual onlyOwner {
                        require(newOwner != address(0), "Ownable: new owner is the zero address");
                        _transferOwnership(newOwner);
                    }
                    /**
                     * @dev Transfers ownership of the contract to a new account (`newOwner`).
                     * Internal function without access restriction.
                     */
                    function _transferOwnership(address newOwner) internal virtual {
                        address oldOwner = _owner;
                        _owner = newOwner;
                        emit OwnershipTransferred(oldOwner, newOwner);
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Interface of the ERC1271 standard signature validation method for
                 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
                 *
                 * _Available since v4.1._
                 */
                interface IERC1271 {
                    /**
                     * @dev Should return whether the signature provided is valid for the provided data
                     * @param hash      Hash of the data to be signed
                     * @param signature Signature byte array associated with _data
                     */
                    function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-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.6.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 v4.4.1 (utils/Context.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Provides information about the current execution context, including the
                 * sender of the transaction and its data. While these are generally available
                 * via msg.sender and msg.data, they should not be accessed in such a direct
                 * manner, since when dealing with meta-transactions the account sending and
                 * paying for execution may not be the actual sender (as far as an application
                 * is concerned).
                 *
                 * This contract is only required for intermediate, library-like contracts.
                 */
                abstract contract Context {
                    function _msgSender() internal view virtual returns (address) {
                        return msg.sender;
                    }
                    function _msgData() internal view virtual returns (bytes calldata) {
                        return msg.data;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                import "@1inch/solidity-utils/contracts/libraries/SafeERC20.sol";
                import "@openzeppelin/contracts/access/Ownable.sol";
                import "./interfaces/IFeeBankCharger.sol";
                import "./interfaces/IFeeBank.sol";
                /// @title Contract with fee mechanism for solvers to pay for using the system
                contract FeeBank is IFeeBank, Ownable {
                    using SafeERC20 for IERC20;
                    IERC20 private immutable _token;
                    IFeeBankCharger private immutable _charger;
                    mapping(address => uint256) private _accountDeposits;
                    constructor(IFeeBankCharger charger, IERC20 inch, address owner) {
                        _charger = charger;
                        _token = inch;
                        transferOwnership(owner);
                    }
                    function availableCredit(address account) external view returns (uint256) {
                        return _charger.availableCredit(account);
                    }
                    /**
                     * @notice Increment sender's availableCredit in Settlement contract.
                     * @param amount The amount of 1INCH sender pay for incresing.
                     * @return totalAvailableCredit The total sender's availableCredit after deposit.
                     */
                    function deposit(uint256 amount) external returns (uint256 totalAvailableCredit) {
                        return _depositFor(msg.sender, amount);
                    }
                    /**
                     * @notice Increases account's availableCredit in Settlement contract.
                     * @param account The account whose availableCredit is increased by the sender.
                     * @param amount The amount of 1INCH sender pay for incresing.
                     * @return totalAvailableCredit The total account's availableCredit after deposit.
                     */
                    function depositFor(address account, uint256 amount) external returns (uint256 totalAvailableCredit) {
                        return _depositFor(account, amount);
                    }
                    /**
                     * @notice See {deposit}. This method uses permit for deposit without prior approves.
                     * @param amount The amount of 1INCH sender pay for incresing.
                     * @param permit The data with sender's permission via token.
                     * @return totalAvailableCredit The total sender's availableCredit after deposit.
                     */
                    function depositWithPermit(uint256 amount, bytes calldata permit) external returns (uint256 totalAvailableCredit) {
                        return depositForWithPermit(msg.sender, amount, permit);
                    }
                    /**
                     * @notice See {depositFor} and {depositWithPermit}.
                     */
                    function depositForWithPermit(
                        address account,
                        uint256 amount,
                        bytes calldata permit
                    ) public returns (uint256 totalAvailableCredit) {
                        _token.safePermit(permit);
                        return _depositFor(account, amount);
                    }
                    /**
                     * @notice Returns unspent availableCredit.
                     * @param amount The amount of 1INCH sender returns.
                     * @return totalAvailableCredit The total sender's availableCredit after withdrawal.
                     */
                    function withdraw(uint256 amount) external returns (uint256 totalAvailableCredit) {
                        return _withdrawTo(msg.sender, amount);
                    }
                    /**
                     * @notice Returns unspent availableCredit to specific account.
                     * @param account The account which get withdrawaled tokens.
                     * @param amount The amount of withdrawaled tokens.
                     * @return totalAvailableCredit The total sender's availableCredit after withdrawal.
                     */
                    function withdrawTo(address account, uint256 amount) external returns (uint256 totalAvailableCredit) {
                        return _withdrawTo(account, amount);
                    }
                    /**
                     * @notice Admin method returns commissions spent by users.
                     * @param accounts Accounts whose commissions are being withdrawn.
                     * @return totalAccountFees The total amount of accounts commissions.
                     */
                    function gatherFees(address[] memory accounts) external onlyOwner returns (uint256 totalAccountFees) {
                        uint256 accountsLength = accounts.length;
                        for (uint256 i = 0; i < accountsLength; ++i) {
                            address account = accounts[i];
                            uint256 accountDeposit = _accountDeposits[account];
                            uint256 availableCredit_ = _charger.availableCredit(account);
                            _accountDeposits[account] = availableCredit_;
                            totalAccountFees += accountDeposit - availableCredit_;
                        }
                        _token.safeTransfer(msg.sender, totalAccountFees);
                    }
                    function _depositFor(address account, uint256 amount) internal returns (uint256 totalAvailableCredit) {
                        _token.safeTransferFrom(msg.sender, address(this), amount);
                        _accountDeposits[account] += amount;
                        totalAvailableCredit = _charger.increaseAvailableCredit(account, amount);
                    }
                    function _withdrawTo(address account, uint256 amount) internal returns (uint256 totalAvailableCredit) {
                        totalAvailableCredit = _charger.decreaseAvailableCredit(msg.sender, amount);
                        _accountDeposits[msg.sender] -= amount;
                        _token.safeTransfer(account, amount);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                import "./interfaces/IFeeBankCharger.sol";
                import "./FeeBank.sol";
                contract FeeBankCharger is IFeeBankCharger {
                    error OnlyFeeBankAccess();
                    error NotEnoughCredit();
                    IFeeBank public immutable feeBank;
                    mapping(address => uint256) private _creditAllowance;
                    modifier onlyFeeBank() {
                        if (msg.sender != address(feeBank)) revert OnlyFeeBankAccess();
                        _;
                    }
                    constructor(IERC20 token) {
                        feeBank = new FeeBank(this, token, msg.sender);
                    }
                    function availableCredit(address account) external view returns (uint256) {
                        return _creditAllowance[account];
                    }
                    function increaseAvailableCredit(address account, uint256 amount) external onlyFeeBank returns (uint256 allowance) {
                        allowance = _creditAllowance[account];
                        allowance += amount;
                        _creditAllowance[account] = allowance;
                    }
                    function decreaseAvailableCredit(address account, uint256 amount) external onlyFeeBank returns (uint256 allowance) {
                        allowance = _creditAllowance[account];
                        allowance -= amount;
                        _creditAllowance[account] = allowance;
                    }
                    function _chargeFee(address account, uint256 fee) internal {
                        if (fee > 0) {
                            uint256 currentAllowance = _creditAllowance[account];
                            if (currentAllowance < fee) revert NotEnoughCredit();
                            unchecked {
                                _creditAllowance[account] = currentAllowance - fee;
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                interface IFeeBank {
                    function deposit(uint256 amount) external returns (uint256 totalAvailableCredit);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                interface IFeeBankCharger {
                    function availableCredit(address account) external view returns (uint256);
                    function increaseAvailableCredit(address account, uint256 amount) external returns (uint256 allowance);
                    function decreaseAvailableCredit(address account, uint256 amount) external returns (uint256 allowance);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import "../libraries/DynamicSuffix.sol";
                interface IResolver {
                    function resolveOrders(address resolver, bytes calldata tokensAndAmounts, bytes calldata data) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import "@1inch/limit-order-protocol-contract/contracts/interfaces/IInteractionNotificationReceiver.sol";
                import "./IFeeBankCharger.sol";
                interface ISettlement is IInteractionNotificationReceiver, IFeeBankCharger {
                    function settleOrders(bytes calldata order) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                type Address is uint256;
                library AddressLib {
                    function get(Address a) internal pure returns (address) {
                        return address(uint160(Address.unwrap(a)));
                    }
                    function getFlag(Address a, uint256 flag) internal pure returns (bool) {
                        return Address.unwrap(a) & flag != 0;
                    }
                    function getUint32(Address a, uint256 offset) internal pure returns (uint32) {
                        return uint32(Address.unwrap(a) >> offset);
                    }
                    function getUint64(Address a, uint256 offset) internal pure returns (uint64) {
                        return uint64(Address.unwrap(a) >> offset);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import "./Address.sol";
                import "./TakingFee.sol";
                // layout of dynamic suffix is as follows:
                // 0x00 - 0x19: totalFee
                // 0x20 - 0x39: resolver
                // 0x40 - 0x59: token
                // 0x60 - 0x79: rateBump
                // 0x80 - 0x99: takingFee
                // 0xa0 - 0x..: tokensAndAmounts bytes
                // 0x.. - 0x..: tokensAndAmounts length in bytes
                library DynamicSuffix {
                    struct Data {
                        uint256 totalFee;
                        Address resolver;
                        Address token;
                        uint256 rateBump;
                        TakingFee.Data takingFee;
                    }
                    uint256 internal constant _STATIC_DATA_SIZE = 0xa0;
                    function decodeSuffix(bytes calldata cd) internal pure returns(Data calldata suffix, bytes calldata tokensAndAmounts, bytes calldata interaction) {
                        assembly {
                            let lengthOffset := sub(add(cd.offset, cd.length), 0x20)
                            tokensAndAmounts.length := calldataload(lengthOffset)
                            tokensAndAmounts.offset := sub(lengthOffset, tokensAndAmounts.length)
                            suffix := sub(tokensAndAmounts.offset, _STATIC_DATA_SIZE)
                            interaction.offset := add(cd.offset, 1)
                            interaction.length := sub(suffix, interaction.offset)
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                /// @title Library for parsing parameters from salt.
                library OrderSaltParser {
                    uint256 private constant _TIME_START_MASK        = 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000; // prettier-ignore
                    uint256 private constant _DURATION_MASK          = 0x00000000FFFFFF00000000000000000000000000000000000000000000000000; // prettier-ignore
                    uint256 private constant _INITIAL_RATE_BUMP_MASK = 0x00000000000000FFFFFF00000000000000000000000000000000000000000000; // prettier-ignore
                    uint256 private constant _FEE_MASK               = 0x00000000000000000000FFFFFFFF000000000000000000000000000000000000; // prettier-ignore
                    uint256 private constant _SALT_MASK              = 0x0000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore
                    uint256 private constant _TIME_START_SHIFT = 224; // orderTimeMask 224-255
                    uint256 private constant _DURATION_SHIFT = 200; // durationMask 200-223
                    uint256 private constant _INITIAL_RATE_BUMP_SHIFT = 176; // initialRateMask 176-200
                    uint256 private constant _FEE_SHIFT = 144; // orderFee 144-175
                    function getStartTime(uint256 salt) internal pure returns (uint256) {
                        return (salt & _TIME_START_MASK) >> _TIME_START_SHIFT;
                    }
                    function getDuration(uint256 salt) internal pure returns (uint256) {
                        return (salt & _DURATION_MASK) >> _DURATION_SHIFT;
                    }
                    function getInitialRateBump(uint256 salt) internal pure returns (uint256) {
                        return (salt & _INITIAL_RATE_BUMP_MASK) >> _INITIAL_RATE_BUMP_SHIFT;
                    }
                    function getFee(uint256 salt) internal pure returns (uint256) {
                        return (salt & _FEE_MASK) >> _FEE_SHIFT;
                    }
                    function getSalt(uint256 salt) internal pure returns (uint256) {
                        return salt & _SALT_MASK;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import "@1inch/limit-order-protocol-contract/contracts/OrderLib.sol";
                import "./OrderSaltParser.sol";
                import "./TakingFee.sol";
                // Placed in the end of the order interactions data
                // Last byte contains flags and lengths, can have up to 15 resolvers and 7 points
                library OrderSuffix {
                    using OrderSaltParser for uint256;
                    // `Order.interactions` suffix structure:
                    // M*(1 + 3 bytes)  - auction points coefficients with seconds delays
                    // N*(4 + 20 bytes) - resolver with corresponding time limit
                    // 4 bytes          - public time limit
                    // 32 bytes         - taking fee (optional if flags has _HAS_TAKING_FEE_FLAG)
                    // 1 bytes          - flags
                    uint256 private constant _HAS_TAKING_FEE_FLAG = 0x80;
                    uint256 private constant _RESOLVERS_LENGTH_MASK = 0x78;
                    uint256 private constant _RESOLVERS_LENGTH_BIT_SHIFT = 3;
                    uint256 private constant _POINTS_LENGTH_MASK = 0x07;
                    uint256 private constant _POINTS_LENGTH_BIT_SHIFT = 0;
                    uint256 private constant _TAKING_FEE_BYTES_SIZE = 32;
                    uint256 private constant _PUBLIC_TIME_LIMIT_BYTES_SIZE = 4;
                    uint256 private constant _PUBLIC_TIME_LIMIT_BIT_SHIFT = 224; // 256 - _PUBLIC_TIME_LIMIT_BYTES_SIZE * 8
                    uint256 private constant _AUCTION_POINT_DELAY_BYTES_SIZE = 2;
                    uint256 private constant _AUCTION_POINT_BUMP_BYTES_SIZE = 3;
                    uint256 private constant _AUCTION_POINT_BYTES_SIZE = 5; // _AUCTION_POINT_DELAY_BYTES_SIZE + _AUCTION_POINT_BUMP_BYTES_SIZE;
                    uint256 private constant _AUCTION_POINT_DELAY_BIT_SHIFT = 240; // 256 - _AUCTION_POINT_DELAY_BYTES_SIZE * 8;
                    uint256 private constant _AUCTION_POINT_BUMP_BIT_SHIFT = 232; // 256 - _AUCTION_POINT_BUMP_BYTES_SIZE * 8;
                    uint256 private constant _RESOLVER_TIME_LIMIT_BYTES_SIZE = 4;
                    uint256 private constant _RESOLVER_ADDRESS_BYTES_SIZE = 20;
                    uint256 private constant _RESOLVER_BYTES_SIZE = 24; // _RESOLVER_TIME_LIMIT_BYTES_SIZE + _RESOLVER_ADDRESS_BYTES_SIZE;
                    uint256 private constant _RESOLVER_TIME_LIMIT_BIT_SHIFT = 224; // 256 - _RESOLVER_TIME_LIMIT_BYTES_SIZE * 8;
                    uint256 private constant _RESOLVER_ADDRESS_BIT_SHIFT = 96; // 256 - _RESOLVER_ADDRESS_BYTES_SIZE * 8;
                    function takingFee(OrderLib.Order calldata order) internal pure returns (TakingFee.Data ret) {
                        bytes calldata interactions = order.interactions;
                        assembly {
                            let ptr := sub(add(interactions.offset, interactions.length), 1)
                            if and(_HAS_TAKING_FEE_FLAG, byte(0, calldataload(ptr))) {
                                ret := calldataload(sub(ptr, _TAKING_FEE_BYTES_SIZE))
                            }
                        }
                    }
                    function checkResolver(OrderLib.Order calldata order, address resolver) internal view returns (bool valid) {
                        bytes calldata interactions = order.interactions;
                        assembly {
                            let ptr := sub(add(interactions.offset, interactions.length), 1)
                            let flags := byte(0, calldataload(ptr))
                            ptr := sub(ptr, _PUBLIC_TIME_LIMIT_BYTES_SIZE)
                            if and(flags, _HAS_TAKING_FEE_FLAG) {
                                ptr := sub(ptr, _TAKING_FEE_BYTES_SIZE)
                            }
                            let resolversCount := shr(_RESOLVERS_LENGTH_BIT_SHIFT, and(flags, _RESOLVERS_LENGTH_MASK))
                            // Check public time limit
                            let publicLimit := shr(_PUBLIC_TIME_LIMIT_BIT_SHIFT, calldataload(ptr))
                            valid := gt(timestamp(), publicLimit)
                            // Check resolvers and corresponding time limits
                            if not(valid) {
                                for { let end := sub(ptr, mul(_RESOLVER_BYTES_SIZE, resolversCount)) } gt(ptr, end) { } {
                                    ptr := sub(ptr, _RESOLVER_ADDRESS_BYTES_SIZE)
                                    let account := shr(_RESOLVER_ADDRESS_BIT_SHIFT, calldataload(ptr))
                                    ptr := sub(ptr, _RESOLVER_TIME_LIMIT_BYTES_SIZE)
                                    let limit := shr(_RESOLVER_TIME_LIMIT_BIT_SHIFT, calldataload(ptr))
                                    if eq(account, resolver) {
                                        valid := iszero(lt(timestamp(), limit))
                                        break
                                    }
                                }
                            }
                        }
                    }
                    function rateBump(OrderLib.Order calldata order) internal view returns (uint256 bump) {
                        uint256 startBump = order.salt.getInitialRateBump();
                        uint256 cumulativeTime = order.salt.getStartTime();
                        uint256 lastTime = cumulativeTime + order.salt.getDuration();
                        if (block.timestamp <= cumulativeTime) {
                            return startBump;
                        } else if (block.timestamp >= lastTime) {
                            return 0;
                        }
                        bytes calldata interactions = order.interactions;
                        assembly {
                            function linearInterpolation(t1, t2, v1, v2, t) -> v {
                                v := div(
                                    add(mul(sub(t, t1), v2), mul(sub(t2, t), v1)),
                                    sub(t2, t1)
                                )
                            }
                            let ptr := sub(add(interactions.offset, interactions.length), 1)
                            // move ptr to the last point
                            let pointsCount
                            {  // stack too deep
                                let flags := byte(0, calldataload(ptr))
                                let resolversCount := shr(_RESOLVERS_LENGTH_BIT_SHIFT, and(flags, _RESOLVERS_LENGTH_MASK))
                                pointsCount := and(flags, _POINTS_LENGTH_MASK)
                                if and(flags, _HAS_TAKING_FEE_FLAG) {
                                    ptr := sub(ptr, _TAKING_FEE_BYTES_SIZE)
                                }
                                ptr := sub(ptr, add(mul(_RESOLVER_BYTES_SIZE, resolversCount), _PUBLIC_TIME_LIMIT_BYTES_SIZE)) // 24 byte for each wl entry + 4 bytes for public time limit
                            }
                            // Check points sequentially
                            let prevCoefficient := startBump
                            let prevCumulativeTime := cumulativeTime
                            for { let end := sub(ptr, mul(_AUCTION_POINT_BYTES_SIZE, pointsCount)) } gt(ptr, end) { } {
                                ptr := sub(ptr, _AUCTION_POINT_BUMP_BYTES_SIZE)
                                let coefficient := shr(_AUCTION_POINT_BUMP_BIT_SHIFT, calldataload(ptr))
                                ptr := sub(ptr, _AUCTION_POINT_DELAY_BYTES_SIZE)
                                let delay := shr(_AUCTION_POINT_DELAY_BIT_SHIFT, calldataload(ptr))
                                cumulativeTime := add(cumulativeTime, delay)
                                if gt(cumulativeTime, timestamp()) {
                                    // prevCumulativeTime <passed> time <elapsed> cumulativeTime
                                    // prevCoefficient    <passed>  X   <elapsed> coefficient
                                    bump := linearInterpolation(
                                        prevCumulativeTime,
                                        cumulativeTime,
                                        prevCoefficient,
                                        coefficient,
                                        timestamp()
                                    )
                                    break
                                }
                                prevCumulativeTime := cumulativeTime
                                prevCoefficient := coefficient
                            }
                            if iszero(bump) {
                                bump := linearInterpolation(
                                    prevCumulativeTime,
                                    lastTime,
                                    prevCoefficient,
                                    0,
                                    timestamp()
                                )
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                library TakingFee {
                    type Data is uint256;
                    uint256 internal constant _TAKING_FEE_BASE = 1e9;
                    uint256 private constant _TAKING_FEE_RATIO_OFFSET = 160;
                    function init(address receiver_, uint256 ratio_) internal pure returns (Data) {
                        if (ratio_ == 0) {
                            return Data.wrap(uint160(receiver_));
                        }
                        return Data.wrap(uint160(receiver_) | (ratio_ << _TAKING_FEE_RATIO_OFFSET));
                    }
                    function enabled(Data self) internal pure returns (bool) {
                        return ratio(self) != 0;
                    }
                    function ratio(Data self) internal pure returns (uint256) {
                        return uint32(Data.unwrap(self) >> _TAKING_FEE_RATIO_OFFSET);
                    }
                    function receiver(Data self) internal pure returns (address) {
                        return address(uint160(Data.unwrap(self)));
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                import "@1inch/limit-order-protocol-contract/contracts/interfaces/IOrderMixin.sol";
                import "@1inch/solidity-utils/contracts/libraries/SafeERC20.sol";
                import "./interfaces/ISettlement.sol";
                import "./interfaces/IResolver.sol";
                import "./libraries/DynamicSuffix.sol";
                import "./libraries/OrderSaltParser.sol";
                import "./libraries/OrderSuffix.sol";
                import "./FeeBankCharger.sol";
                contract Settlement is ISettlement, FeeBankCharger {
                    using SafeERC20 for IERC20;
                    using OrderSaltParser for uint256;
                    using DynamicSuffix for bytes;
                    using AddressLib for Address;
                    using OrderSuffix for OrderLib.Order;
                    using TakingFee for TakingFee.Data;
                    error AccessDenied();
                    error IncorrectCalldataParams();
                    error FailedExternalCall();
                    error ResolverIsNotWhitelisted();
                    error WrongInteractionTarget();
                    bytes1 private constant _FINALIZE_INTERACTION = 0x01;
                    uint256 private constant _ORDER_FEE_BASE_POINTS = 1e15;
                    uint256 private constant _BASE_POINTS = 10_000_000; // 100%
                    IOrderMixin private immutable _limitOrderProtocol;
                    modifier onlyThis(address account) {
                        if (account != address(this)) revert AccessDenied();
                        _;
                    }
                    modifier onlyLimitOrderProtocol {
                        if (msg.sender != address(_limitOrderProtocol)) revert AccessDenied();
                        _;
                    }
                    constructor(IOrderMixin limitOrderProtocol, IERC20 token)
                        FeeBankCharger(token)
                    {
                        _limitOrderProtocol = limitOrderProtocol;
                    }
                    function settleOrders(bytes calldata data) external {
                        _settleOrder(data, msg.sender, 0, new bytes(0));
                    }
                    function fillOrderInteraction(
                        address taker,
                        uint256, /* makingAmount */
                        uint256 takingAmount,
                        bytes calldata interactiveData
                    ) external onlyThis(taker) onlyLimitOrderProtocol returns (uint256 result) {
                        (DynamicSuffix.Data calldata suffix, bytes calldata tokensAndAmounts, bytes calldata interaction) = interactiveData.decodeSuffix();
                        IERC20 token = IERC20(suffix.token.get());
                        result = takingAmount * (_BASE_POINTS + suffix.rateBump) / _BASE_POINTS;
                        uint256 takingFee = result * suffix.takingFee.ratio() / TakingFee._TAKING_FEE_BASE;
                        bytes memory allTokensAndAmounts = new bytes(tokensAndAmounts.length + 0x40);
                        assembly {
                            let ptr := add(allTokensAndAmounts, 0x20)
                            calldatacopy(ptr, tokensAndAmounts.offset, tokensAndAmounts.length)
                            ptr := add(ptr, tokensAndAmounts.length)
                            mstore(ptr, token)
                            mstore(add(ptr, 0x20), add(result, takingFee))
                        }
                        if (interactiveData[0] == _FINALIZE_INTERACTION) {
                            _chargeFee(suffix.resolver.get(), suffix.totalFee);
                            address target = address(bytes20(interaction));
                            bytes calldata data = interaction[20:];
                            IResolver(target).resolveOrders(suffix.resolver.get(), allTokensAndAmounts, data);
                        } else {
                            _settleOrder(
                                interaction,
                                suffix.resolver.get(),
                                suffix.totalFee,
                                allTokensAndAmounts
                            );
                        }
                        if (takingFee > 0) {
                            token.safeTransfer(suffix.takingFee.receiver(), takingFee);
                        }
                        token.forceApprove(address(_limitOrderProtocol), result);
                    }
                    bytes4 private constant _FILL_ORDER_TO_SELECTOR = 0xe5d7bde6; // IOrderMixin.fillOrderTo.selector
                    bytes4 private constant _WRONG_INTERACTION_TARGET_SELECTOR = 0x5b34bf89; // WrongInteractionTarget.selector
                    function _settleOrder(bytes calldata data, address resolver, uint256 totalFee, bytes memory tokensAndAmounts) private {
                        OrderLib.Order calldata order;
                        assembly {
                            order := add(data.offset, calldataload(data.offset))
                        }
                        if (!order.checkResolver(resolver)) revert ResolverIsNotWhitelisted();
                        TakingFee.Data takingFeeData = order.takingFee();
                        totalFee += order.salt.getFee() * _ORDER_FEE_BASE_POINTS;
                        uint256 rateBump = order.rateBump();
                        uint256 suffixLength = DynamicSuffix._STATIC_DATA_SIZE + tokensAndAmounts.length + 0x20;
                        IOrderMixin limitOrderProtocol = _limitOrderProtocol;
                        assembly {
                            function memcpy(dst, src, len) {
                                pop(staticcall(gas(), 0x4, src, len, dst, len))
                            }
                            let interactionLengthOffset := calldataload(add(data.offset, 0x40))
                            let interactionOffset := add(interactionLengthOffset, 0x20)
                            let interactionLength := calldataload(add(data.offset, interactionLengthOffset))
                            { // stack too deep
                                let target := shr(96, calldataload(add(data.offset, interactionOffset)))
                                if or(lt(interactionLength, 20), iszero(eq(target, address()))) {
                                    mstore(0, _WRONG_INTERACTION_TARGET_SELECTOR)
                                    revert(0, 4)
                                }
                            }
                            // Copy calldata and patch interaction.length
                            let ptr := mload(0x40)
                            mstore(ptr, _FILL_ORDER_TO_SELECTOR)
                            calldatacopy(add(ptr, 4), data.offset, data.length)
                            mstore(add(add(ptr, interactionLengthOffset), 4), add(interactionLength, suffixLength))
                            {  // stack too deep
                                // Append suffix fields
                                let offset := add(add(ptr, interactionOffset), interactionLength)
                                mstore(add(offset, 0x04), totalFee)
                                mstore(add(offset, 0x24), resolver)
                                mstore(add(offset, 0x44), calldataload(add(order, 0x40)))  // takerAsset
                                mstore(add(offset, 0x64), rateBump)
                                mstore(add(offset, 0x84), takingFeeData)
                                let tokensAndAmountsLength := mload(tokensAndAmounts)
                                memcpy(add(offset, 0xa4), add(tokensAndAmounts, 0x20), tokensAndAmountsLength)
                                mstore(add(offset, add(0xa4, tokensAndAmountsLength)), tokensAndAmountsLength)
                            }
                            // Call fillOrderTo
                            if iszero(call(gas(), limitOrderProtocol, 0, ptr, add(add(4, suffixLength), data.length), ptr, 0)) {
                                returndatacopy(ptr, 0, returndatasize())
                                revert(ptr, returndatasize())
                            }
                        }
                    }
                }
                

                File 4 of 5: WETH9
                // Copyright (C) 2015, 2016, 2017 Dapphub
                
                // This program is free software: you can redistribute it and/or modify
                // it under the terms of the GNU General Public License as published by
                // the Free Software Foundation, either version 3 of the License, or
                // (at your option) any later version.
                
                // This program is distributed in the hope that it will be useful,
                // but WITHOUT ANY WARRANTY; without even the implied warranty of
                // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                // GNU General Public License for more details.
                
                // You should have received a copy of the GNU General Public License
                // along with this program.  If not, see <http://www.gnu.org/licenses/>.
                
                pragma solidity ^0.4.18;
                
                contract WETH9 {
                    string public name     = "Wrapped Ether";
                    string public symbol   = "WETH";
                    uint8  public decimals = 18;
                
                    event  Approval(address indexed src, address indexed guy, uint wad);
                    event  Transfer(address indexed src, address indexed dst, uint wad);
                    event  Deposit(address indexed dst, uint wad);
                    event  Withdrawal(address indexed src, uint wad);
                
                    mapping (address => uint)                       public  balanceOf;
                    mapping (address => mapping (address => uint))  public  allowance;
                
                    function() public payable {
                        deposit();
                    }
                    function deposit() public payable {
                        balanceOf[msg.sender] += msg.value;
                        Deposit(msg.sender, msg.value);
                    }
                    function withdraw(uint wad) public {
                        require(balanceOf[msg.sender] >= wad);
                        balanceOf[msg.sender] -= wad;
                        msg.sender.transfer(wad);
                        Withdrawal(msg.sender, wad);
                    }
                
                    function totalSupply() public view returns (uint) {
                        return this.balance;
                    }
                
                    function approve(address guy, uint wad) public returns (bool) {
                        allowance[msg.sender][guy] = wad;
                        Approval(msg.sender, guy, wad);
                        return true;
                    }
                
                    function transfer(address dst, uint wad) public returns (bool) {
                        return transferFrom(msg.sender, dst, wad);
                    }
                
                    function transferFrom(address src, address dst, uint wad)
                        public
                        returns (bool)
                    {
                        require(balanceOf[src] >= wad);
                
                        if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
                            require(allowance[src][msg.sender] >= wad);
                            allowance[src][msg.sender] -= wad;
                        }
                
                        balanceOf[src] -= wad;
                        balanceOf[dst] += wad;
                
                        Transfer(src, dst, wad);
                
                        return true;
                    }
                }
                
                
                /*
                                    GNU GENERAL PUBLIC LICENSE
                                       Version 3, 29 June 2007
                
                 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
                 Everyone is permitted to copy and distribute verbatim copies
                 of this license document, but changing it is not allowed.
                
                                            Preamble
                
                  The GNU General Public License is a free, copyleft license for
                software and other kinds of works.
                
                  The licenses for most software and other practical works are designed
                to take away your freedom to share and change the works.  By contrast,
                the GNU General Public License is intended to guarantee your freedom to
                share and change all versions of a program--to make sure it remains free
                software for all its users.  We, the Free Software Foundation, use the
                GNU General Public License for most of our software; it applies also to
                any other work released this way by its authors.  You can apply it to
                your programs, too.
                
                  When we speak of free software, we are referring to freedom, not
                price.  Our General Public Licenses are designed to make sure that you
                have the freedom to distribute copies of free software (and charge for
                them if you wish), that you receive source code or can get it if you
                want it, that you can change the software or use pieces of it in new
                free programs, and that you know you can do these things.
                
                  To protect your rights, we need to prevent others from denying you
                these rights or asking you to surrender the rights.  Therefore, you have
                certain responsibilities if you distribute copies of the software, or if
                you modify it: responsibilities to respect the freedom of others.
                
                  For example, if you distribute copies of such a program, whether
                gratis or for a fee, you must pass on to the recipients the same
                freedoms that you received.  You must make sure that they, too, receive
                or can get the source code.  And you must show them these terms so they
                know their rights.
                
                  Developers that use the GNU GPL protect your rights with two steps:
                (1) assert copyright on the software, and (2) offer you this License
                giving you legal permission to copy, distribute and/or modify it.
                
                  For the developers' and authors' protection, the GPL clearly explains
                that there is no warranty for this free software.  For both users' and
                authors' sake, the GPL requires that modified versions be marked as
                changed, so that their problems will not be attributed erroneously to
                authors of previous versions.
                
                  Some devices are designed to deny users access to install or run
                modified versions of the software inside them, although the manufacturer
                can do so.  This is fundamentally incompatible with the aim of
                protecting users' freedom to change the software.  The systematic
                pattern of such abuse occurs in the area of products for individuals to
                use, which is precisely where it is most unacceptable.  Therefore, we
                have designed this version of the GPL to prohibit the practice for those
                products.  If such problems arise substantially in other domains, we
                stand ready to extend this provision to those domains in future versions
                of the GPL, as needed to protect the freedom of users.
                
                  Finally, every program is threatened constantly by software patents.
                States should not allow patents to restrict development and use of
                software on general-purpose computers, but in those that do, we wish to
                avoid the special danger that patents applied to a free program could
                make it effectively proprietary.  To prevent this, the GPL assures that
                patents cannot be used to render the program non-free.
                
                  The precise terms and conditions for copying, distribution and
                modification follow.
                
                                       TERMS AND CONDITIONS
                
                  0. Definitions.
                
                  "This License" refers to version 3 of the GNU General Public License.
                
                  "Copyright" also means copyright-like laws that apply to other kinds of
                works, such as semiconductor masks.
                
                  "The Program" refers to any copyrightable work licensed under this
                License.  Each licensee is addressed as "you".  "Licensees" and
                "recipients" may be individuals or organizations.
                
                  To "modify" a work means to copy from or adapt all or part of the work
                in a fashion requiring copyright permission, other than the making of an
                exact copy.  The resulting work is called a "modified version" of the
                earlier work or a work "based on" the earlier work.
                
                  A "covered work" means either the unmodified Program or a work based
                on the Program.
                
                  To "propagate" a work means to do anything with it that, without
                permission, would make you directly or secondarily liable for
                infringement under applicable copyright law, except executing it on a
                computer or modifying a private copy.  Propagation includes copying,
                distribution (with or without modification), making available to the
                public, and in some countries other activities as well.
                
                  To "convey" a work means any kind of propagation that enables other
                parties to make or receive copies.  Mere interaction with a user through
                a computer network, with no transfer of a copy, is not conveying.
                
                  An interactive user interface displays "Appropriate Legal Notices"
                to the extent that it includes a convenient and prominently visible
                feature that (1) displays an appropriate copyright notice, and (2)
                tells the user that there is no warranty for the work (except to the
                extent that warranties are provided), that licensees may convey the
                work under this License, and how to view a copy of this License.  If
                the interface presents a list of user commands or options, such as a
                menu, a prominent item in the list meets this criterion.
                
                  1. Source Code.
                
                  The "source code" for a work means the preferred form of the work
                for making modifications to it.  "Object code" means any non-source
                form of a work.
                
                  A "Standard Interface" means an interface that either is an official
                standard defined by a recognized standards body, or, in the case of
                interfaces specified for a particular programming language, one that
                is widely used among developers working in that language.
                
                  The "System Libraries" of an executable work include anything, other
                than the work as a whole, that (a) is included in the normal form of
                packaging a Major Component, but which is not part of that Major
                Component, and (b) serves only to enable use of the work with that
                Major Component, or to implement a Standard Interface for which an
                implementation is available to the public in source code form.  A
                "Major Component", in this context, means a major essential component
                (kernel, window system, and so on) of the specific operating system
                (if any) on which the executable work runs, or a compiler used to
                produce the work, or an object code interpreter used to run it.
                
                  The "Corresponding Source" for a work in object code form means all
                the source code needed to generate, install, and (for an executable
                work) run the object code and to modify the work, including scripts to
                control those activities.  However, it does not include the work's
                System Libraries, or general-purpose tools or generally available free
                programs which are used unmodified in performing those activities but
                which are not part of the work.  For example, Corresponding Source
                includes interface definition files associated with source files for
                the work, and the source code for shared libraries and dynamically
                linked subprograms that the work is specifically designed to require,
                such as by intimate data communication or control flow between those
                subprograms and other parts of the work.
                
                  The Corresponding Source need not include anything that users
                can regenerate automatically from other parts of the Corresponding
                Source.
                
                  The Corresponding Source for a work in source code form is that
                same work.
                
                  2. Basic Permissions.
                
                  All rights granted under this License are granted for the term of
                copyright on the Program, and are irrevocable provided the stated
                conditions are met.  This License explicitly affirms your unlimited
                permission to run the unmodified Program.  The output from running a
                covered work is covered by this License only if the output, given its
                content, constitutes a covered work.  This License acknowledges your
                rights of fair use or other equivalent, as provided by copyright law.
                
                  You may make, run and propagate covered works that you do not
                convey, without conditions so long as your license otherwise remains
                in force.  You may convey covered works to others for the sole purpose
                of having them make modifications exclusively for you, or provide you
                with facilities for running those works, provided that you comply with
                the terms of this License in conveying all material for which you do
                not control copyright.  Those thus making or running the covered works
                for you must do so exclusively on your behalf, under your direction
                and control, on terms that prohibit them from making any copies of
                your copyrighted material outside their relationship with you.
                
                  Conveying under any other circumstances is permitted solely under
                the conditions stated below.  Sublicensing is not allowed; section 10
                makes it unnecessary.
                
                  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
                
                  No covered work shall be deemed part of an effective technological
                measure under any applicable law fulfilling obligations under article
                11 of the WIPO copyright treaty adopted on 20 December 1996, or
                similar laws prohibiting or restricting circumvention of such
                measures.
                
                  When you convey a covered work, you waive any legal power to forbid
                circumvention of technological measures to the extent such circumvention
                is effected by exercising rights under this License with respect to
                the covered work, and you disclaim any intention to limit operation or
                modification of the work as a means of enforcing, against the work's
                users, your or third parties' legal rights to forbid circumvention of
                technological measures.
                
                  4. Conveying Verbatim Copies.
                
                  You may convey verbatim copies of the Program's source code as you
                receive it, in any medium, provided that you conspicuously and
                appropriately publish on each copy an appropriate copyright notice;
                keep intact all notices stating that this License and any
                non-permissive terms added in accord with section 7 apply to the code;
                keep intact all notices of the absence of any warranty; and give all
                recipients a copy of this License along with the Program.
                
                  You may charge any price or no price for each copy that you convey,
                and you may offer support or warranty protection for a fee.
                
                  5. Conveying Modified Source Versions.
                
                  You may convey a work based on the Program, or the modifications to
                produce it from the Program, in the form of source code under the
                terms of section 4, provided that you also meet all of these conditions:
                
                    a) The work must carry prominent notices stating that you modified
                    it, and giving a relevant date.
                
                    b) The work must carry prominent notices stating that it is
                    released under this License and any conditions added under section
                    7.  This requirement modifies the requirement in section 4 to
                    "keep intact all notices".
                
                    c) You must license the entire work, as a whole, under this
                    License to anyone who comes into possession of a copy.  This
                    License will therefore apply, along with any applicable section 7
                    additional terms, to the whole of the work, and all its parts,
                    regardless of how they are packaged.  This License gives no
                    permission to license the work in any other way, but it does not
                    invalidate such permission if you have separately received it.
                
                    d) If the work has interactive user interfaces, each must display
                    Appropriate Legal Notices; however, if the Program has interactive
                    interfaces that do not display Appropriate Legal Notices, your
                    work need not make them do so.
                
                  A compilation of a covered work with other separate and independent
                works, which are not by their nature extensions of the covered work,
                and which are not combined with it such as to form a larger program,
                in or on a volume of a storage or distribution medium, is called an
                "aggregate" if the compilation and its resulting copyright are not
                used to limit the access or legal rights of the compilation's users
                beyond what the individual works permit.  Inclusion of a covered work
                in an aggregate does not cause this License to apply to the other
                parts of the aggregate.
                
                  6. Conveying Non-Source Forms.
                
                  You may convey a covered work in object code form under the terms
                of sections 4 and 5, provided that you also convey the
                machine-readable Corresponding Source under the terms of this License,
                in one of these ways:
                
                    a) Convey the object code in, or embodied in, a physical product
                    (including a physical distribution medium), accompanied by the
                    Corresponding Source fixed on a durable physical medium
                    customarily used for software interchange.
                
                    b) Convey the object code in, or embodied in, a physical product
                    (including a physical distribution medium), accompanied by a
                    written offer, valid for at least three years and valid for as
                    long as you offer spare parts or customer support for that product
                    model, to give anyone who possesses the object code either (1) a
                    copy of the Corresponding Source for all the software in the
                    product that is covered by this License, on a durable physical
                    medium customarily used for software interchange, for a price no
                    more than your reasonable cost of physically performing this
                    conveying of source, or (2) access to copy the
                    Corresponding Source from a network server at no charge.
                
                    c) Convey individual copies of the object code with a copy of the
                    written offer to provide the Corresponding Source.  This
                    alternative is allowed only occasionally and noncommercially, and
                    only if you received the object code with such an offer, in accord
                    with subsection 6b.
                
                    d) Convey the object code by offering access from a designated
                    place (gratis or for a charge), and offer equivalent access to the
                    Corresponding Source in the same way through the same place at no
                    further charge.  You need not require recipients to copy the
                    Corresponding Source along with the object code.  If the place to
                    copy the object code is a network server, the Corresponding Source
                    may be on a different server (operated by you or a third party)
                    that supports equivalent copying facilities, provided you maintain
                    clear directions next to the object code saying where to find the
                    Corresponding Source.  Regardless of what server hosts the
                    Corresponding Source, you remain obligated to ensure that it is
                    available for as long as needed to satisfy these requirements.
                
                    e) Convey the object code using peer-to-peer transmission, provided
                    you inform other peers where the object code and Corresponding
                    Source of the work are being offered to the general public at no
                    charge under subsection 6d.
                
                  A separable portion of the object code, whose source code is excluded
                from the Corresponding Source as a System Library, need not be
                included in conveying the object code work.
                
                  A "User Product" is either (1) a "consumer product", which means any
                tangible personal property which is normally used for personal, family,
                or household purposes, or (2) anything designed or sold for incorporation
                into a dwelling.  In determining whether a product is a consumer product,
                doubtful cases shall be resolved in favor of coverage.  For a particular
                product received by a particular user, "normally used" refers to a
                typical or common use of that class of product, regardless of the status
                of the particular user or of the way in which the particular user
                actually uses, or expects or is expected to use, the product.  A product
                is a consumer product regardless of whether the product has substantial
                commercial, industrial or non-consumer uses, unless such uses represent
                the only significant mode of use of the product.
                
                  "Installation Information" for a User Product means any methods,
                procedures, authorization keys, or other information required to install
                and execute modified versions of a covered work in that User Product from
                a modified version of its Corresponding Source.  The information must
                suffice to ensure that the continued functioning of the modified object
                code is in no case prevented or interfered with solely because
                modification has been made.
                
                  If you convey an object code work under this section in, or with, or
                specifically for use in, a User Product, and the conveying occurs as
                part of a transaction in which the right of possession and use of the
                User Product is transferred to the recipient in perpetuity or for a
                fixed term (regardless of how the transaction is characterized), the
                Corresponding Source conveyed under this section must be accompanied
                by the Installation Information.  But this requirement does not apply
                if neither you nor any third party retains the ability to install
                modified object code on the User Product (for example, the work has
                been installed in ROM).
                
                  The requirement to provide Installation Information does not include a
                requirement to continue to provide support service, warranty, or updates
                for a work that has been modified or installed by the recipient, or for
                the User Product in which it has been modified or installed.  Access to a
                network may be denied when the modification itself materially and
                adversely affects the operation of the network or violates the rules and
                protocols for communication across the network.
                
                  Corresponding Source conveyed, and Installation Information provided,
                in accord with this section must be in a format that is publicly
                documented (and with an implementation available to the public in
                source code form), and must require no special password or key for
                unpacking, reading or copying.
                
                  7. Additional Terms.
                
                  "Additional permissions" are terms that supplement the terms of this
                License by making exceptions from one or more of its conditions.
                Additional permissions that are applicable to the entire Program shall
                be treated as though they were included in this License, to the extent
                that they are valid under applicable law.  If additional permissions
                apply only to part of the Program, that part may be used separately
                under those permissions, but the entire Program remains governed by
                this License without regard to the additional permissions.
                
                  When you convey a copy of a covered work, you may at your option
                remove any additional permissions from that copy, or from any part of
                it.  (Additional permissions may be written to require their own
                removal in certain cases when you modify the work.)  You may place
                additional permissions on material, added by you to a covered work,
                for which you have or can give appropriate copyright permission.
                
                  Notwithstanding any other provision of this License, for material you
                add to a covered work, you may (if authorized by the copyright holders of
                that material) supplement the terms of this License with terms:
                
                    a) Disclaiming warranty or limiting liability differently from the
                    terms of sections 15 and 16 of this License; or
                
                    b) Requiring preservation of specified reasonable legal notices or
                    author attributions in that material or in the Appropriate Legal
                    Notices displayed by works containing it; or
                
                    c) Prohibiting misrepresentation of the origin of that material, or
                    requiring that modified versions of such material be marked in
                    reasonable ways as different from the original version; or
                
                    d) Limiting the use for publicity purposes of names of licensors or
                    authors of the material; or
                
                    e) Declining to grant rights under trademark law for use of some
                    trade names, trademarks, or service marks; or
                
                    f) Requiring indemnification of licensors and authors of that
                    material by anyone who conveys the material (or modified versions of
                    it) with contractual assumptions of liability to the recipient, for
                    any liability that these contractual assumptions directly impose on
                    those licensors and authors.
                
                  All other non-permissive additional terms are considered "further
                restrictions" within the meaning of section 10.  If the Program as you
                received it, or any part of it, contains a notice stating that it is
                governed by this License along with a term that is a further
                restriction, you may remove that term.  If a license document contains
                a further restriction but permits relicensing or conveying under this
                License, you may add to a covered work material governed by the terms
                of that license document, provided that the further restriction does
                not survive such relicensing or conveying.
                
                  If you add terms to a covered work in accord with this section, you
                must place, in the relevant source files, a statement of the
                additional terms that apply to those files, or a notice indicating
                where to find the applicable terms.
                
                  Additional terms, permissive or non-permissive, may be stated in the
                form of a separately written license, or stated as exceptions;
                the above requirements apply either way.
                
                  8. Termination.
                
                  You may not propagate or modify a covered work except as expressly
                provided under this License.  Any attempt otherwise to propagate or
                modify it is void, and will automatically terminate your rights under
                this License (including any patent licenses granted under the third
                paragraph of section 11).
                
                  However, if you cease all violation of this License, then your
                license from a particular copyright holder is reinstated (a)
                provisionally, unless and until the copyright holder explicitly and
                finally terminates your license, and (b) permanently, if the copyright
                holder fails to notify you of the violation by some reasonable means
                prior to 60 days after the cessation.
                
                  Moreover, your license from a particular copyright holder is
                reinstated permanently if the copyright holder notifies you of the
                violation by some reasonable means, this is the first time you have
                received notice of violation of this License (for any work) from that
                copyright holder, and you cure the violation prior to 30 days after
                your receipt of the notice.
                
                  Termination of your rights under this section does not terminate the
                licenses of parties who have received copies or rights from you under
                this License.  If your rights have been terminated and not permanently
                reinstated, you do not qualify to receive new licenses for the same
                material under section 10.
                
                  9. Acceptance Not Required for Having Copies.
                
                  You are not required to accept this License in order to receive or
                run a copy of the Program.  Ancillary propagation of a covered work
                occurring solely as a consequence of using peer-to-peer transmission
                to receive a copy likewise does not require acceptance.  However,
                nothing other than this License grants you permission to propagate or
                modify any covered work.  These actions infringe copyright if you do
                not accept this License.  Therefore, by modifying or propagating a
                covered work, you indicate your acceptance of this License to do so.
                
                  10. Automatic Licensing of Downstream Recipients.
                
                  Each time you convey a covered work, the recipient automatically
                receives a license from the original licensors, to run, modify and
                propagate that work, subject to this License.  You are not responsible
                for enforcing compliance by third parties with this License.
                
                  An "entity transaction" is a transaction transferring control of an
                organization, or substantially all assets of one, or subdividing an
                organization, or merging organizations.  If propagation of a covered
                work results from an entity transaction, each party to that
                transaction who receives a copy of the work also receives whatever
                licenses to the work the party's predecessor in interest had or could
                give under the previous paragraph, plus a right to possession of the
                Corresponding Source of the work from the predecessor in interest, if
                the predecessor has it or can get it with reasonable efforts.
                
                  You may not impose any further restrictions on the exercise of the
                rights granted or affirmed under this License.  For example, you may
                not impose a license fee, royalty, or other charge for exercise of
                rights granted under this License, and you may not initiate litigation
                (including a cross-claim or counterclaim in a lawsuit) alleging that
                any patent claim is infringed by making, using, selling, offering for
                sale, or importing the Program or any portion of it.
                
                  11. Patents.
                
                  A "contributor" is a copyright holder who authorizes use under this
                License of the Program or a work on which the Program is based.  The
                work thus licensed is called the contributor's "contributor version".
                
                  A contributor's "essential patent claims" are all patent claims
                owned or controlled by the contributor, whether already acquired or
                hereafter acquired, that would be infringed by some manner, permitted
                by this License, of making, using, or selling its contributor version,
                but do not include claims that would be infringed only as a
                consequence of further modification of the contributor version.  For
                purposes of this definition, "control" includes the right to grant
                patent sublicenses in a manner consistent with the requirements of
                this License.
                
                  Each contributor grants you a non-exclusive, worldwide, royalty-free
                patent license under the contributor's essential patent claims, to
                make, use, sell, offer for sale, import and otherwise run, modify and
                propagate the contents of its contributor version.
                
                  In the following three paragraphs, a "patent license" is any express
                agreement or commitment, however denominated, not to enforce a patent
                (such as an express permission to practice a patent or covenant not to
                sue for patent infringement).  To "grant" such a patent license to a
                party means to make such an agreement or commitment not to enforce a
                patent against the party.
                
                  If you convey a covered work, knowingly relying on a patent license,
                and the Corresponding Source of the work is not available for anyone
                to copy, free of charge and under the terms of this License, through a
                publicly available network server or other readily accessible means,
                then you must either (1) cause the Corresponding Source to be so
                available, or (2) arrange to deprive yourself of the benefit of the
                patent license for this particular work, or (3) arrange, in a manner
                consistent with the requirements of this License, to extend the patent
                license to downstream recipients.  "Knowingly relying" means you have
                actual knowledge that, but for the patent license, your conveying the
                covered work in a country, or your recipient's use of the covered work
                in a country, would infringe one or more identifiable patents in that
                country that you have reason to believe are valid.
                
                  If, pursuant to or in connection with a single transaction or
                arrangement, you convey, or propagate by procuring conveyance of, a
                covered work, and grant a patent license to some of the parties
                receiving the covered work authorizing them to use, propagate, modify
                or convey a specific copy of the covered work, then the patent license
                you grant is automatically extended to all recipients of the covered
                work and works based on it.
                
                  A patent license is "discriminatory" if it does not include within
                the scope of its coverage, prohibits the exercise of, or is
                conditioned on the non-exercise of one or more of the rights that are
                specifically granted under this License.  You may not convey a covered
                work if you are a party to an arrangement with a third party that is
                in the business of distributing software, under which you make payment
                to the third party based on the extent of your activity of conveying
                the work, and under which the third party grants, to any of the
                parties who would receive the covered work from you, a discriminatory
                patent license (a) in connection with copies of the covered work
                conveyed by you (or copies made from those copies), or (b) primarily
                for and in connection with specific products or compilations that
                contain the covered work, unless you entered into that arrangement,
                or that patent license was granted, prior to 28 March 2007.
                
                  Nothing in this License shall be construed as excluding or limiting
                any implied license or other defenses to infringement that may
                otherwise be available to you under applicable patent law.
                
                  12. No Surrender of Others' Freedom.
                
                  If conditions are imposed on you (whether by court order, agreement or
                otherwise) that contradict the conditions of this License, they do not
                excuse you from the conditions of this License.  If you cannot convey a
                covered work so as to satisfy simultaneously your obligations under this
                License and any other pertinent obligations, then as a consequence you may
                not convey it at all.  For example, if you agree to terms that obligate you
                to collect a royalty for further conveying from those to whom you convey
                the Program, the only way you could satisfy both those terms and this
                License would be to refrain entirely from conveying the Program.
                
                  13. Use with the GNU Affero General Public License.
                
                  Notwithstanding any other provision of this License, you have
                permission to link or combine any covered work with a work licensed
                under version 3 of the GNU Affero General Public License into a single
                combined work, and to convey the resulting work.  The terms of this
                License will continue to apply to the part which is the covered work,
                but the special requirements of the GNU Affero General Public License,
                section 13, concerning interaction through a network will apply to the
                combination as such.
                
                  14. Revised Versions of this License.
                
                  The Free Software Foundation may publish revised and/or new versions of
                the GNU General Public License from time to time.  Such new versions will
                be similar in spirit to the present version, but may differ in detail to
                address new problems or concerns.
                
                  Each version is given a distinguishing version number.  If the
                Program specifies that a certain numbered version of the GNU General
                Public License "or any later version" applies to it, you have the
                option of following the terms and conditions either of that numbered
                version or of any later version published by the Free Software
                Foundation.  If the Program does not specify a version number of the
                GNU General Public License, you may choose any version ever published
                by the Free Software Foundation.
                
                  If the Program specifies that a proxy can decide which future
                versions of the GNU General Public License can be used, that proxy's
                public statement of acceptance of a version permanently authorizes you
                to choose that version for the Program.
                
                  Later license versions may give you additional or different
                permissions.  However, no additional obligations are imposed on any
                author or copyright holder as a result of your choosing to follow a
                later version.
                
                  15. Disclaimer of Warranty.
                
                  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
                APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
                HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
                OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
                THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
                PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
                IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
                ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
                
                  16. Limitation of Liability.
                
                  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
                THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
                GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
                USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
                DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
                PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
                EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
                SUCH DAMAGES.
                
                  17. Interpretation of Sections 15 and 16.
                
                  If the disclaimer of warranty and limitation of liability provided
                above cannot be given local legal effect according to their terms,
                reviewing courts shall apply local law that most closely approximates
                an absolute waiver of all civil liability in connection with the
                Program, unless a warranty or assumption of liability accompanies a
                copy of the Program in return for a fee.
                
                                     END OF TERMS AND CONDITIONS
                
                            How to Apply These Terms to Your New Programs
                
                  If you develop a new program, and you want it to be of the greatest
                possible use to the public, the best way to achieve this is to make it
                free software which everyone can redistribute and change under these terms.
                
                  To do so, attach the following notices to the program.  It is safest
                to attach them to the start of each source file to most effectively
                state the exclusion of warranty; and each file should have at least
                the "copyright" line and a pointer to where the full notice is found.
                
                    <one line to give the program's name and a brief idea of what it does.>
                    Copyright (C) <year>  <name of author>
                
                    This program is free software: you can redistribute it and/or modify
                    it under the terms of the GNU General Public License as published by
                    the Free Software Foundation, either version 3 of the License, or
                    (at your option) any later version.
                
                    This program is distributed in the hope that it will be useful,
                    but WITHOUT ANY WARRANTY; without even the implied warranty of
                    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    GNU General Public License for more details.
                
                    You should have received a copy of the GNU General Public License
                    along with this program.  If not, see <http://www.gnu.org/licenses/>.
                
                Also add information on how to contact you by electronic and paper mail.
                
                  If the program does terminal interaction, make it output a short
                notice like this when it starts in an interactive mode:
                
                    <program>  Copyright (C) <year>  <name of author>
                    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
                    This is free software, and you are welcome to redistribute it
                    under certain conditions; type `show c' for details.
                
                The hypothetical commands `show w' and `show c' should show the appropriate
                parts of the General Public License.  Of course, your program's commands
                might be different; for a GUI interface, you would use an "about box".
                
                  You should also get your employer (if you work as a programmer) or school,
                if any, to sign a "copyright disclaimer" for the program, if necessary.
                For more information on this, and how to apply and follow the GNU GPL, see
                <http://www.gnu.org/licenses/>.
                
                  The GNU General Public License does not permit incorporating your program
                into proprietary programs.  If your program is a subroutine library, you
                may consider it more useful to permit linking proprietary applications with
                the library.  If this is what you want to do, use the GNU Lesser General
                Public License instead of this License.  But first, please read
                <http://www.gnu.org/philosophy/why-not-lgpl.html>.
                
                */

                File 5 of 5: WethUnwrapper
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                pragma abicoder v1;
                import "@1inch/solidity-utils/contracts/OnlyWethReceiver.sol";
                import "@1inch/solidity-utils/contracts/interfaces/IWETH.sol";
                import "../interfaces/IPostInteractionNotificationReceiver.sol";
                import "../libraries/Errors.sol";
                contract WethUnwrapper is OnlyWethReceiver, IPostInteractionNotificationReceiver {
                    IWETH private immutable _WETH;  // solhint-disable-line var-name-mixedcase
                    uint256 private constant _RAW_CALL_GAS_LIMIT = 5000;
                    constructor(IWETH weth) OnlyWethReceiver(address(weth)) {
                        _WETH = weth;
                    }
                    function fillOrderPostInteraction(
                        bytes32 /* orderHash */,
                        address maker,
                        address /* taker */,
                        uint256 /* makingAmount */,
                        uint256 takingAmount,
                        uint256 /* remainingMakerAmount */,
                        bytes calldata interactiveData
                    ) external override {
                        _WETH.withdraw(takingAmount);
                        address receiver = maker;
                        if (interactiveData.length == 20) {
                            receiver = address(bytes20(interactiveData));
                        }
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, ) = receiver.call{value: takingAmount, gas: _RAW_CALL_GAS_LIMIT}("");
                        if (!success) revert Errors.ETHTransferFailed();
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                library Errors {
                    error InvalidMsgValue();
                    error ETHTransferFailed();
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.17;
                pragma abicoder v1;
                /**
                 * @title Interface for interactor which acts after `taker -> maker` transfers.
                 * @notice The order filling steps are `preInteraction` =>` Transfer "maker -> taker"` => `Interaction` => `Transfer "taker -> maker"` => **`postInteraction`**
                 */
                interface IPostInteractionNotificationReceiver {
                    /**
                     * @notice Callback method that gets called after all funds transfers
                     * @param orderHash Hash of the order being processed
                     * @param maker Maker address
                     * @param taker Taker address
                     * @param makingAmount Actual making amount
                     * @param takingAmount Actual taking amount
                     * @param remainingAmount Limit order remaining maker amount after the swap
                     * @param interactionData Interaction calldata
                     */
                    function fillOrderPostInteraction(
                        bytes32 orderHash,
                        address maker,
                        address taker,
                        uint256 makingAmount,
                        uint256 takingAmount,
                        uint256 remainingAmount,
                        bytes memory interactionData
                    ) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                pragma abicoder v1;
                import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                interface IWETH is IERC20 {
                    function deposit() external payable;
                    function withdraw(uint256 amount) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                pragma abicoder v1;
                import "./EthReceiver.sol";
                abstract contract OnlyWethReceiver is EthReceiver {
                    address private immutable _WETH; // solhint-disable-line var-name-mixedcase
                    constructor(address weth) {
                        _WETH = address(weth);
                    }
                    function _receive() internal virtual override {
                        if (msg.sender != _WETH) revert EthDepositRejected();
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.6.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.0;
                pragma abicoder v1;
                abstract contract EthReceiver {
                    error EthDepositRejected();
                    receive() external payable {
                        _receive();
                    }
                    function _receive() internal virtual {
                        // solhint-disable-next-line avoid-tx-origin
                        if (msg.sender == tx.origin) revert EthDepositRejected();
                    }
                }