ETH Price: $2,014.00 (+2.98%)

Transaction Decoder

Block:
16507193 at Jan-28-2023 06:45:35 PM +UTC
Transaction Fee:
0.004389746260232441 ETH $8.84
Gas Used:
271,213 Gas / 16.185604157 Gwei

Emitted Events:

296 Permit2.Permit( owner=[Sender] 0xbb02fef81914b820037079f29a2f9152dbcf3e75, token=AdminUpgradeabilityProxy, spender=[Receiver] UniversalRouter, amount=1461501637330902918203684832716283019655932542975, expiration=1677523412, nonce=0 )
297 AdminUpgradeabilityProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000bb02fef81914b820037079f29a2f9152dbcf3e75, 0x000000000000000000000000ea7952fac7ff6e997d895c1566599b86b91444c0, 0000000000000000000000000000000000000000000001a5c5ac16f63b4e0000 )
298 Dai.Transfer( src=UniswapV2Pair, dst=UniswapV2Pair, wad=34450328675540985519 )
299 UniswapV2Pair.Sync( reserve0=5924665572192538373342, reserve1=1341803143324045647789871 )
300 UniswapV2Pair.Swap( sender=[Receiver] UniversalRouter, amount0In=0, amount1In=7780323040000000000000, amount0Out=34450328675540985519, amount1Out=0, to=UniswapV2Pair )
301 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000ae461ca67b15dc8dc81ce7615e0320da1a9ab8d5, 0x000000000000000000000000bb02fef81914b820037079f29a2f9152dbcf3e75, 00000000000000000000000000000000000000000000000000000000020c76ad )
302 UniswapV2Pair.Sync( reserve0=17833087893438168992968231, reserve1=17845653412577 )
303 UniswapV2Pair.Swap( sender=[Receiver] UniversalRouter, amount0In=34450328675540985519, amount1In=0, amount0Out=0, amount1Out=34371245, to=[Sender] 0xbb02fef81914b820037079f29a2f9152dbcf3e75 )

Account State Difference:

  Address   Before After State Difference Code
0x00000000...43aC78BA3
(Uniswap Protocol: Permit2)
0x6B175474...495271d0F
(beaverbuild)
242.508208294929200856 Eth242.508479507929200856 Eth0.000271213
0xA0b86991...E3606eB48
0xAE461cA6...A1A9aB8D5
0xbb02fEf8...2DBcF3e75
0.082409056824053472 Eth
Nonce: 20
0.078019310563821031 Eth
Nonce: 21
0.004389746260232441
0xDd1Ad9A2...c868cE9a4
0xeA7952FA...6b91444C0

Execution Trace

UniversalRouter.execute( commands=0x0A08, inputs=[AAAAAAAAAAAAAAAA3RrZohznIsFRqDY3O6vkLIaM6aQAAAAAAAAAAAAAAAD//////////////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj/PnUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADvHG5ncDx71xB+7YMD++bsJVS/awAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj1XPcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQW+UFJBTrTvt3G5fyq8YbL697SYKgyEH6vnIN2u77zxzUasBHO7ElZQwsZNuwUu30mJhDHv+WPURERUy7ULV0ZgbAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==, AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaXFrBb2O04AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACBcX0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAA3RrZohznIsFRqDY3O6vkLIaM6aQAAAAAAAAAAAAAAABrF1R06JCUxE2pi5VO7erElScdDwAAAAAAAAAAAAAAAKC4aZHGIYs2wdGdSi6esM42ButI], deadline=1674933299 )
  • Permit2.permit( owner=0xbb02fEf81914b820037079F29A2F9152DBcF3e75, permitSingle=[{name:details, type:tuple, order:1, indexed:false, value:[{name:token, type:address, order:1, indexed:false, value:0xDd1Ad9A21Ce722C151A836373baBe42c868cE9a4, valueString:0xDd1Ad9A21Ce722C151A836373baBe42c868cE9a4}, {name:amount, type:uint160, order:2, indexed:false, value:1461501637330902918203684832716283019655932542975, valueString:1461501637330902918203684832716283019655932542975}, {name:expiration, type:uint48, order:3, indexed:false, value:1677523412, valueString:1677523412}, {name:nonce, type:uint48, order:4, indexed:false, value:0, valueString:0}], valueString:[{name:token, type:address, order:1, indexed:false, value:0xDd1Ad9A21Ce722C151A836373baBe42c868cE9a4, valueString:0xDd1Ad9A21Ce722C151A836373baBe42c868cE9a4}, {name:amount, type:uint160, order:2, indexed:false, value:1461501637330902918203684832716283019655932542975, valueString:1461501637330902918203684832716283019655932542975}, {name:expiration, type:uint48, order:3, indexed:false, value:1677523412, valueString:1677523412}, {name:nonce, type:uint48, order:4, indexed:false, value:0, valueString:0}]}, {name:spender, type:address, order:2, indexed:false, value:0xEf1c6E67703c7BD7107eed8303Fbe6EC2554BF6B, valueString:0xEf1c6E67703c7BD7107eed8303Fbe6EC2554BF6B}, {name:sigDeadline, type:uint256, order:3, indexed:false, value:1674933212, valueString:1674933212}], signature=0x6F94149053AD3BEDDC6E5FCAAF186CBEBDED260A832107EAF9C8376BBBEF3C7351AB011CEEC4959430B1936EC14BB7D262610C7BFE58F511111532ED42D5D1981B )
    • Null: 0x000...001.0aa92f86( )
    • Permit2.transferFrom( from=0xbb02fEf81914b820037079F29A2F9152DBcF3e75, to=0xeA7952FAC7Ff6e997d895C1566599b86b91444C0, amount=7780323040000000000000, token=0xDd1Ad9A21Ce722C151A836373baBe42c868cE9a4 )
      • AdminUpgradeabilityProxy.23b872dd( )
        • UBI.transferFrom( _sender=0xbb02fEf81914b820037079F29A2F9152DBcF3e75, _recipient=0xeA7952FAC7Ff6e997d895C1566599b86b91444C0, _amount=7780323040000000000000 ) => ( True )
          • ProofOfHumanity.isRegistered( _submissionID=0xbb02fEf81914b820037079F29A2F9152DBcF3e75 ) => ( True )
          • FiatTokenProxy.70a08231( )
            • FiatTokenV2_1.balanceOf( account=0xbb02fEf81914b820037079F29A2F9152DBcF3e75 ) => ( 0 )
            • UniswapV2Pair.STATICCALL( )
            • AdminUpgradeabilityProxy.70a08231( )
              • UBI.balanceOf( _human=0xeA7952FAC7Ff6e997d895C1566599b86b91444C0 ) => ( 1341803143324045647789871 )
              • UniswapV2Pair.swap( amount0Out=34450328675540985519, amount1Out=0, to=0xAE461cA67B15dc8dc81CE7615e0320dA1A9aB8D5, data=0x )
                • Dai.transfer( dst=0xAE461cA67B15dc8dc81CE7615e0320dA1A9aB8D5, wad=34450328675540985519 ) => ( True )
                • Dai.balanceOf( 0xeA7952FAC7Ff6e997d895C1566599b86b91444C0 ) => ( 5924665572192538373342 )
                • AdminUpgradeabilityProxy.70a08231( )
                  • UBI.balanceOf( _human=0xeA7952FAC7Ff6e997d895C1566599b86b91444C0 ) => ( 1341803143324045647789871 )
                  • UniswapV2Pair.STATICCALL( )
                  • Dai.balanceOf( 0xAE461cA67B15dc8dc81CE7615e0320dA1A9aB8D5 ) => ( 17833087893438168992968231 )
                  • UniswapV2Pair.swap( amount0Out=0, amount1Out=34371245, to=0xbb02fEf81914b820037079F29A2F9152DBcF3e75, data=0x )
                    • FiatTokenProxy.a9059cbb( )
                      • FiatTokenV2_1.transfer( to=0xbb02fEf81914b820037079F29A2F9152DBcF3e75, value=34371245 ) => ( True )
                      • Dai.balanceOf( 0xAE461cA67B15dc8dc81CE7615e0320dA1A9aB8D5 ) => ( 17833087893438168992968231 )
                      • FiatTokenProxy.70a08231( )
                        • FiatTokenV2_1.balanceOf( account=0xAE461cA67B15dc8dc81CE7615e0320dA1A9aB8D5 ) => ( 17845653412577 )
                        • FiatTokenProxy.70a08231( )
                          • FiatTokenV2_1.balanceOf( account=0xbb02fEf81914b820037079F29A2F9152DBcF3e75 ) => ( 34371245 )
                            File 1 of 10: UniversalRouter
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.17;
                            import {Dispatcher} from './base/Dispatcher.sol';
                            import {RewardsCollector} from './base/RewardsCollector.sol';
                            import {RouterParameters, RouterImmutables} from './base/RouterImmutables.sol';
                            import {Constants} from './libraries/Constants.sol';
                            import {Commands} from './libraries/Commands.sol';
                            import {IUniversalRouter} from './interfaces/IUniversalRouter.sol';
                            import {ReentrancyLock} from './base/ReentrancyLock.sol';
                            contract UniversalRouter is RouterImmutables, IUniversalRouter, Dispatcher, RewardsCollector, ReentrancyLock {
                                modifier checkDeadline(uint256 deadline) {
                                    if (block.timestamp > deadline) revert TransactionDeadlinePassed();
                                    _;
                                }
                                constructor(RouterParameters memory params) RouterImmutables(params) {}
                                /// @inheritdoc IUniversalRouter
                                function execute(bytes calldata commands, bytes[] calldata inputs, uint256 deadline)
                                    external
                                    payable
                                    checkDeadline(deadline)
                                {
                                    execute(commands, inputs);
                                }
                                /// @inheritdoc IUniversalRouter
                                function execute(bytes calldata commands, bytes[] calldata inputs) public payable isNotLocked {
                                    bool success;
                                    bytes memory output;
                                    uint256 numCommands = commands.length;
                                    if (inputs.length != numCommands) revert LengthMismatch();
                                    // loop through all given commands, execute them and pass along outputs as defined
                                    for (uint256 commandIndex = 0; commandIndex < numCommands;) {
                                        bytes1 command = commands[commandIndex];
                                        bytes memory input = inputs[commandIndex];
                                        (success, output) = dispatch(command, input);
                                        if (!success && successRequired(command)) {
                                            revert ExecutionFailed({commandIndex: commandIndex, message: output});
                                        }
                                        unchecked {
                                            commandIndex++;
                                        }
                                    }
                                }
                                function successRequired(bytes1 command) internal pure returns (bool) {
                                    return command & Commands.FLAG_ALLOW_REVERT == 0;
                                }
                                // To receive ETH from WETH and NFT protocols
                                receive() external payable {}
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.17;
                            import {IERC721Receiver} from 'openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol';
                            import {IERC1155Receiver} from 'openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol';
                            import {IERC165} from 'openzeppelin-contracts/contracts/utils/introspection/IERC165.sol';
                            /// @title ERC Callback Support
                            /// @notice Implements various functions introduced by a variety of ERCs for security reasons.
                            /// All are called by external contracts to ensure that this contract safely supports the ERC in question.
                            contract Callbacks is IERC721Receiver, IERC1155Receiver {
                                function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
                                    return this.onERC721Received.selector;
                                }
                                function onERC1155Received(address, address, uint256, uint256, bytes calldata) external pure returns (bytes4) {
                                    return this.onERC1155Received.selector;
                                }
                                function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata, bytes calldata)
                                    external
                                    pure
                                    returns (bytes4)
                                {
                                    return this.onERC1155BatchReceived.selector;
                                }
                                function supportsInterface(bytes4 interfaceId) external pure returns (bool) {
                                    return interfaceId == type(IERC1155Receiver).interfaceId || interfaceId == type(IERC721Receiver).interfaceId
                                        || interfaceId == type(IERC165).interfaceId;
                                }
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.17;
                            import {V2SwapRouter} from '../modules/uniswap/v2/V2SwapRouter.sol';
                            import {V3SwapRouter} from '../modules/uniswap/v3/V3SwapRouter.sol';
                            import {Payments} from '../modules/Payments.sol';
                            import {RouterImmutables} from '../base/RouterImmutables.sol';
                            import {Callbacks} from '../base/Callbacks.sol';
                            import {Commands} from '../libraries/Commands.sol';
                            import {Recipient} from '../libraries/Recipient.sol';
                            import {ERC721} from 'solmate/tokens/ERC721.sol';
                            import {ERC1155} from 'solmate/tokens/ERC1155.sol';
                            import {IAllowanceTransfer} from 'permit2/src/interfaces/IAllowanceTransfer.sol';
                            import {ICryptoPunksMarket} from '../interfaces/external/ICryptoPunksMarket.sol';
                            /// @title Decodes and Executes Commands
                            /// @notice Called by the UniversalRouter contract to efficiently decode and execute a singular command
                            abstract contract Dispatcher is Payments, V2SwapRouter, V3SwapRouter, Callbacks {
                                using Recipient for address;
                                error InvalidCommandType(uint256 commandType);
                                error InvalidOwnerERC721();
                                error InvalidOwnerERC1155();
                                /// @notice Decodes and executes the given command with the given inputs
                                /// @param commandType The command type to execute
                                /// @param inputs The inputs to execute the command with
                                /// @dev 2 masks are used to enable use of a nested-if statement in execution for efficiency reasons
                                /// @return success True on success of the command, false on failure
                                /// @return output The outputs or error messages, if any, from the command
                                function dispatch(bytes1 commandType, bytes memory inputs) internal returns (bool success, bytes memory output) {
                                    uint256 command = uint8(commandType & Commands.COMMAND_TYPE_MASK);
                                    success = true;
                                    if (command < 0x10) {
                                        // 0x00 <= command < 0x08
                                        if (command < 0x08) {
                                            if (command == Commands.V3_SWAP_EXACT_IN) {
                                                (address recipient, uint256 amountIn, uint256 amountOutMin, bytes memory path, bool payerIsUser) =
                                                    abi.decode(inputs, (address, uint256, uint256, bytes, bool));
                                                address payer = payerIsUser ? msg.sender : address(this);
                                                v3SwapExactInput(recipient.map(), amountIn, amountOutMin, path, payer);
                                            } else if (command == Commands.V3_SWAP_EXACT_OUT) {
                                                (address recipient, uint256 amountOut, uint256 amountInMax, bytes memory path, bool payerIsUser) =
                                                    abi.decode(inputs, (address, uint256, uint256, bytes, bool));
                                                address payer = payerIsUser ? msg.sender : address(this);
                                                v3SwapExactOutput(recipient.map(), amountOut, amountInMax, path, payer);
                                            } else if (command == Commands.PERMIT2_TRANSFER_FROM) {
                                                (address token, address recipient, uint160 amount) = abi.decode(inputs, (address, address, uint160));
                                                permit2TransferFrom(token, msg.sender, recipient, amount);
                                            } else if (command == Commands.PERMIT2_PERMIT_BATCH) {
                                                (IAllowanceTransfer.PermitBatch memory permitBatch, bytes memory data) =
                                                    abi.decode(inputs, (IAllowanceTransfer.PermitBatch, bytes));
                                                PERMIT2.permit(msg.sender, permitBatch, data);
                                            } else if (command == Commands.SWEEP) {
                                                (address token, address recipient, uint256 amountMin) =
                                                    abi.decode(inputs, (address, address, uint256));
                                                Payments.sweep(token, recipient.map(), amountMin);
                                            } else if (command == Commands.TRANSFER) {
                                                (address token, address recipient, uint256 value) = abi.decode(inputs, (address, address, uint256));
                                                Payments.pay(token, recipient.map(), value);
                                            } else if (command == Commands.PAY_PORTION) {
                                                (address token, address recipient, uint256 bips) = abi.decode(inputs, (address, address, uint256));
                                                Payments.payPortion(token, recipient.map(), bips);
                                            } else if (command == Commands.COMMAND_PLACEHOLDER_0x07) {
                                                // placeholder for a future command
                                                revert InvalidCommandType(command);
                                            }
                                            // 0x08 <= command < 0x10
                                        } else {
                                            if (command == Commands.V2_SWAP_EXACT_IN) {
                                                (address recipient, uint256 amountIn, uint256 amountOutMin, address[] memory path, bool payerIsUser)
                                                = abi.decode(inputs, (address, uint256, uint256, address[], bool));
                                                address payer = payerIsUser ? msg.sender : address(this);
                                                v2SwapExactInput(recipient.map(), amountIn, amountOutMin, path, payer);
                                            } else if (command == Commands.V2_SWAP_EXACT_OUT) {
                                                (address recipient, uint256 amountOut, uint256 amountInMax, address[] memory path, bool payerIsUser)
                                                = abi.decode(inputs, (address, uint256, uint256, address[], bool));
                                                address payer = payerIsUser ? msg.sender : address(this);
                                                v2SwapExactOutput(recipient.map(), amountOut, amountInMax, path, payer);
                                            } else if (command == Commands.PERMIT2_PERMIT) {
                                                (IAllowanceTransfer.PermitSingle memory permitSingle, bytes memory data) =
                                                    abi.decode(inputs, (IAllowanceTransfer.PermitSingle, bytes));
                                                PERMIT2.permit(msg.sender, permitSingle, data);
                                            } else if (command == Commands.WRAP_ETH) {
                                                (address recipient, uint256 amountMin) = abi.decode(inputs, (address, uint256));
                                                Payments.wrapETH(recipient.map(), amountMin);
                                            } else if (command == Commands.UNWRAP_WETH) {
                                                (address recipient, uint256 amountMin) = abi.decode(inputs, (address, uint256));
                                                Payments.unwrapWETH9(recipient.map(), amountMin);
                                            } else if (command == Commands.PERMIT2_TRANSFER_FROM_BATCH) {
                                                (IAllowanceTransfer.AllowanceTransferDetails[] memory batchDetails) =
                                                    abi.decode(inputs, (IAllowanceTransfer.AllowanceTransferDetails[]));
                                                permit2TransferFrom(batchDetails);
                                            } else if (command == Commands.COMMAND_PLACEHOLDER_0x0e) {
                                                // placeholder for a future command
                                                revert InvalidCommandType(command);
                                            } else if (command == Commands.COMMAND_PLACEHOLDER_0x0f) {
                                                // placeholder for a future command
                                                revert InvalidCommandType(command);
                                            }
                                        }
                                        // 0x10 <= command
                                    } else {
                                        // 0x10 <= command < 0x18
                                        if (command < 0x18) {
                                            if (command == Commands.SEAPORT) {
                                                (uint256 value, bytes memory data) = abi.decode(inputs, (uint256, bytes));
                                                (success, output) = SEAPORT.call{value: value}(data);
                                            } else if (command == Commands.LOOKS_RARE_721) {
                                                (success, output) = callAndTransfer721(inputs, LOOKS_RARE);
                                            } else if (command == Commands.NFTX) {
                                                (uint256 value, bytes memory data) = abi.decode(inputs, (uint256, bytes));
                                                (success, output) = NFTX_ZAP.call{value: value}(data);
                                            } else if (command == Commands.CRYPTOPUNKS) {
                                                (uint256 punkId, address recipient, uint256 value) = abi.decode(inputs, (uint256, address, uint256));
                                                (success, output) = CRYPTOPUNKS.call{value: value}(
                                                    abi.encodeWithSelector(ICryptoPunksMarket.buyPunk.selector, punkId)
                                                );
                                                if (success) ICryptoPunksMarket(CRYPTOPUNKS).transferPunk(recipient.map(), punkId);
                                                else output = 'CryptoPunk Trade Failed';
                                            } else if (command == Commands.LOOKS_RARE_1155) {
                                                (success, output) = callAndTransfer1155(inputs, LOOKS_RARE);
                                            } else if (command == Commands.OWNER_CHECK_721) {
                                                (address owner, address token, uint256 id) = abi.decode(inputs, (address, address, uint256));
                                                success = (ERC721(token).ownerOf(id) == owner);
                                                if (!success) output = abi.encodeWithSignature('InvalidOwnerERC721()');
                                            } else if (command == Commands.OWNER_CHECK_1155) {
                                                (address owner, address token, uint256 id, uint256 minBalance) =
                                                    abi.decode(inputs, (address, address, uint256, uint256));
                                                success = (ERC1155(token).balanceOf(owner, id) >= minBalance);
                                                if (!success) output = abi.encodeWithSignature('InvalidOwnerERC1155()');
                                            } else if (command == Commands.SWEEP_ERC721) {
                                                (address token, address recipient, uint256 id) = abi.decode(inputs, (address, address, uint256));
                                                Payments.sweepERC721(token, recipient.map(), id);
                                            }
                                            // 0x18 <= command < 0x1f
                                        } else {
                                            if (command == Commands.X2Y2_721) {
                                                (success, output) = callAndTransfer721(inputs, X2Y2);
                                            } else if (command == Commands.SUDOSWAP) {
                                                (uint256 value, bytes memory data) = abi.decode(inputs, (uint256, bytes));
                                                (success, output) = SUDOSWAP.call{value: value}(data);
                                            } else if (command == Commands.NFT20) {
                                                (uint256 value, bytes memory data) = abi.decode(inputs, (uint256, bytes));
                                                (success, output) = NFT20_ZAP.call{value: value}(data);
                                            } else if (command == Commands.X2Y2_1155) {
                                                (success, output) = callAndTransfer1155(inputs, X2Y2);
                                            } else if (command == Commands.FOUNDATION) {
                                                (success, output) = callAndTransfer721(inputs, FOUNDATION);
                                            } else if (command == Commands.SWEEP_ERC1155) {
                                                (address token, address recipient, uint256 id, uint256 amount) =
                                                    abi.decode(inputs, (address, address, uint256, uint256));
                                                Payments.sweepERC1155(token, recipient.map(), id, amount);
                                            } else if (command == Commands.COMMAND_PLACEHOLDER_0x1e) {
                                                // placeholder for a future command
                                                revert InvalidCommandType(command);
                                            } else if (command == Commands.COMMAND_PLACEHOLDER_0x1f) {
                                                // placeholder for a future command
                                                revert InvalidCommandType(command);
                                            }
                                        }
                                    }
                                }
                                /// @notice Performs a call to purchase an ERC721, then transfers the ERC721 to a specified recipient
                                /// @param inputs The inputs for the protocol and ERC721 transfer, encoded
                                /// @param protocol The protocol to pass the calldata to
                                /// @return success True on success of the command, false on failure
                                /// @return output The outputs or error messages, if any, from the command
                                function callAndTransfer721(bytes memory inputs, address protocol)
                                    internal
                                    returns (bool success, bytes memory output)
                                {
                                    (uint256 value, bytes memory data, address recipient, address token, uint256 id) =
                                        abi.decode(inputs, (uint256, bytes, address, address, uint256));
                                    (success, output) = protocol.call{value: value}(data);
                                    if (success) ERC721(token).safeTransferFrom(address(this), recipient.map(), id);
                                }
                                /// @notice Performs a call to purchase an ERC1155, then transfers the ERC1155 to a specified recipient
                                /// @param inputs The inputs for the protocol and ERC1155 transfer, encoded
                                /// @param protocol The protocol to pass the calldata to
                                /// @return success True on success of the command, false on failure
                                /// @return output The outputs or error messages, if any, from the command
                                function callAndTransfer1155(bytes memory inputs, address protocol)
                                    internal
                                    returns (bool success, bytes memory output)
                                {
                                    (uint256 value, bytes memory data, address recipient, address token, uint256 id, uint256 amount) =
                                        abi.decode(inputs, (uint256, bytes, address, address, uint256, uint256));
                                    (success, output) = protocol.call{value: value}(data);
                                    if (success) ERC1155(token).safeTransferFrom(address(this), recipient.map(), id, amount, new bytes(0));
                                }
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.17;
                            contract ReentrancyLock {
                                error ContractLocked();
                                uint256 private isLocked = 1;
                                modifier isNotLocked() {
                                    if (isLocked != 1) revert ContractLocked();
                                    isLocked = 2;
                                    _;
                                    isLocked = 1;
                                }
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.15;
                            import {ERC20} from 'solmate/tokens/ERC20.sol';
                            import {SafeTransferLib} from 'solmate/utils/SafeTransferLib.sol';
                            import {RouterImmutables} from './RouterImmutables.sol';
                            import {IRewardsCollector} from '../interfaces/IRewardsCollector.sol';
                            abstract contract RewardsCollector is IRewardsCollector, RouterImmutables {
                                using SafeTransferLib for ERC20;
                                event RewardsSent(uint256 amount);
                                error UnableToClaim();
                                /// @inheritdoc IRewardsCollector
                                function collectRewards(bytes calldata looksRareClaim) external {
                                    (bool success,) = LOOKS_RARE_REWARDS_DISTRIBUTOR.call(looksRareClaim);
                                    if (!success) revert UnableToClaim();
                                    uint256 balance = LOOKS_RARE_TOKEN.balanceOf(address(this));
                                    LOOKS_RARE_TOKEN.transfer(ROUTER_REWARDS_DISTRIBUTOR, balance);
                                    emit RewardsSent(balance);
                                }
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.17;
                            import {IAllowanceTransfer} from 'permit2/src/interfaces/IAllowanceTransfer.sol';
                            import {ERC20} from 'solmate/tokens/ERC20.sol';
                            import {IWETH9} from '../interfaces/external/IWETH9.sol';
                            struct RouterParameters {
                                address permit2;
                                address weth9;
                                address seaport;
                                address nftxZap;
                                address x2y2;
                                address foundation;
                                address sudoswap;
                                address nft20Zap;
                                address cryptopunks;
                                address looksRare;
                                address routerRewardsDistributor;
                                address looksRareRewardsDistributor;
                                address looksRareToken;
                                address v2Factory;
                                address v3Factory;
                                bytes32 pairInitCodeHash;
                                bytes32 poolInitCodeHash;
                            }
                            /// @title Router Immutable Storage contract
                            /// @notice Used along with the `RouterParameters` struct for ease of cross-chain deployment
                            contract RouterImmutables {
                                /// @dev WETH9 address
                                IWETH9 internal immutable WETH9;
                                /// @dev Permit2 address
                                IAllowanceTransfer internal immutable PERMIT2;
                                /// @dev Seaport address
                                address internal immutable SEAPORT;
                                /// @dev The address of NFTX zap contract for interfacing with vaults
                                address internal immutable NFTX_ZAP;
                                /// @dev The address of X2Y2
                                address internal immutable X2Y2;
                                // @dev The address of Foundation
                                address internal immutable FOUNDATION;
                                // @dev The address of Sudoswap's router
                                address internal immutable SUDOSWAP;
                                // @dev the address of NFT20's zap contract
                                address internal immutable NFT20_ZAP;
                                // @dev the address of Larva Lab's cryptopunks marketplace
                                address internal immutable CRYPTOPUNKS;
                                /// @dev The address of LooksRare
                                address internal immutable LOOKS_RARE;
                                /// @dev The address of LooksRare token
                                ERC20 internal immutable LOOKS_RARE_TOKEN;
                                /// @dev The address of LooksRare rewards distributor
                                address internal immutable LOOKS_RARE_REWARDS_DISTRIBUTOR;
                                /// @dev The address of router rewards distributor
                                address internal immutable ROUTER_REWARDS_DISTRIBUTOR;
                                /// @dev The address of UniswapV2Factory
                                address internal immutable UNISWAP_V2_FACTORY;
                                /// @dev The address of UniswapV2Pair initcodehash
                                bytes32 internal immutable UNISWAP_V2_PAIR_INIT_CODE_HASH;
                                /// @dev The address of UniswapV3Factory
                                address internal immutable UNISWAP_V3_FACTORY;
                                /// @dev The address of UniswapV3Pool initcodehash
                                bytes32 internal immutable UNISWAP_V3_POOL_INIT_CODE_HASH;
                                constructor(RouterParameters memory params) {
                                    PERMIT2 = IAllowanceTransfer(params.permit2);
                                    WETH9 = IWETH9(params.weth9);
                                    SEAPORT = params.seaport;
                                    NFTX_ZAP = params.nftxZap;
                                    X2Y2 = params.x2y2;
                                    FOUNDATION = params.foundation;
                                    SUDOSWAP = params.sudoswap;
                                    NFT20_ZAP = params.nft20Zap;
                                    CRYPTOPUNKS = params.cryptopunks;
                                    LOOKS_RARE = params.looksRare;
                                    LOOKS_RARE_TOKEN = ERC20(params.looksRareToken);
                                    LOOKS_RARE_REWARDS_DISTRIBUTOR = params.looksRareRewardsDistributor;
                                    ROUTER_REWARDS_DISTRIBUTOR = params.routerRewardsDistributor;
                                    UNISWAP_V2_FACTORY = params.v2Factory;
                                    UNISWAP_V2_PAIR_INIT_CODE_HASH = params.pairInitCodeHash;
                                    UNISWAP_V3_FACTORY = params.v3Factory;
                                    UNISWAP_V3_POOL_INIT_CODE_HASH = params.poolInitCodeHash;
                                }
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.15;
                            import {ERC20} from 'solmate/tokens/ERC20.sol';
                            /// @title LooksRare Rewards Collector
                            /// @notice Implements a permissionless call to fetch LooksRare rewards earned by Universal Router users
                            /// and transfers them to an external rewards distributor contract
                            interface IRewardsCollector {
                                /// @notice Fetches users' LooksRare rewards and sends them to the distributor contract
                                /// @param looksRareClaim The data required by LooksRare to claim reward tokens
                                function collectRewards(bytes calldata looksRareClaim) external;
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.17;
                            import {IERC721Receiver} from 'openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol';
                            import {IERC1155Receiver} from 'openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol';
                            import {IRewardsCollector} from './IRewardsCollector.sol';
                            interface IUniversalRouter is IRewardsCollector, IERC721Receiver, IERC1155Receiver {
                                /// @notice Thrown when a required command has failed
                                error ExecutionFailed(uint256 commandIndex, bytes message);
                                /// @notice Thrown when attempting to send ETH directly to the contract
                                error ETHNotAccepted();
                                /// @notice Thrown executing commands with an expired deadline
                                error TransactionDeadlinePassed();
                                /// @notice Thrown executing commands with an expired deadline
                                error LengthMismatch();
                                /// @notice Executes encoded commands along with provided inputs. Reverts if deadline has expired.
                                /// @param commands A set of concatenated commands, each 1 byte in length
                                /// @param inputs An array of byte strings containing abi encoded inputs for each command
                                /// @param deadline The deadline by which the transaction must be executed
                                function execute(bytes calldata commands, bytes[] calldata inputs, uint256 deadline) external payable;
                                /// @notice Executes encoded commands along with provided inputs.
                                /// @param commands A set of concatenated commands, each 1 byte in length
                                /// @param inputs An array of byte strings containing abi encoded inputs for each command
                                function execute(bytes calldata commands, bytes[] calldata inputs) external payable;
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.4;
                            /// @title Interface for CryptoPunksMarket
                            interface ICryptoPunksMarket {
                                /// @notice Buy a cryptopunk
                                function buyPunk(uint256 punkIndex) external payable;
                                /// @notice Transfer a cryptopunk to another address
                                function transferPunk(address to, uint256 punkIndex) external;
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.4;
                            import {IERC20} from 'openzeppelin-contracts/contracts/token/ERC20/IERC20.sol';
                            /// @title Interface for WETH9
                            interface IWETH9 is IERC20 {
                                /// @notice Deposit ether to get wrapped ether
                                function deposit() external payable;
                                /// @notice Withdraw wrapped ether to get ether
                                function withdraw(uint256) external;
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.17;
                            /// @title Commands
                            /// @notice Command Flags used to decode commands
                            library Commands {
                                // Masks to extract certain bits of commands
                                bytes1 internal constant FLAG_ALLOW_REVERT = 0x80;
                                bytes1 internal constant COMMAND_TYPE_MASK = 0x1f;
                                bytes1 internal constant NFT_TYPE_MASK = 0x10;
                                bytes1 internal constant SUB_IF_BRANCH_MASK = 0x08;
                                // Command Types. Maximum supported command at this moment is 0x1F.
                                // Command Types where value<0x08, executed in the first nested-if block
                                uint256 constant V3_SWAP_EXACT_IN = 0x00;
                                uint256 constant V3_SWAP_EXACT_OUT = 0x01;
                                uint256 constant PERMIT2_TRANSFER_FROM = 0x02;
                                uint256 constant PERMIT2_PERMIT_BATCH = 0x03;
                                uint256 constant SWEEP = 0x04;
                                uint256 constant TRANSFER = 0x05;
                                uint256 constant PAY_PORTION = 0x06;
                                uint256 constant COMMAND_PLACEHOLDER_0x07 = 0x07;
                                // Command Types where 0x08<=value<=0x0f, executed in the second nested-if block
                                uint256 constant V2_SWAP_EXACT_IN = 0x08;
                                uint256 constant V2_SWAP_EXACT_OUT = 0x09;
                                uint256 constant PERMIT2_PERMIT = 0x0a;
                                uint256 constant WRAP_ETH = 0x0b;
                                uint256 constant UNWRAP_WETH = 0x0c;
                                uint256 constant PERMIT2_TRANSFER_FROM_BATCH = 0x0d;
                                uint256 constant COMMAND_PLACEHOLDER_0x0e = 0x0e;
                                uint256 constant COMMAND_PLACEHOLDER_0x0f = 0x0f;
                                // Command Types where 0x10<=value<0x18, executed in the third nested-if block
                                uint256 constant SEAPORT = 0x10;
                                uint256 constant LOOKS_RARE_721 = 0x11;
                                uint256 constant NFTX = 0x12;
                                uint256 constant CRYPTOPUNKS = 0x13;
                                uint256 constant LOOKS_RARE_1155 = 0x14;
                                uint256 constant OWNER_CHECK_721 = 0x15;
                                uint256 constant OWNER_CHECK_1155 = 0x16;
                                uint256 constant SWEEP_ERC721 = 0x17;
                                // Command Types where 0x18<=value<=0x1f, executed in the final nested-if block
                                uint256 constant X2Y2_721 = 0x18;
                                uint256 constant SUDOSWAP = 0x19;
                                uint256 constant NFT20 = 0x1a;
                                uint256 constant X2Y2_1155 = 0x1b;
                                uint256 constant FOUNDATION = 0x1c;
                                uint256 constant SWEEP_ERC1155 = 0x1d;
                                uint256 constant COMMAND_PLACEHOLDER_0x1e = 0x1e;
                                uint256 constant COMMAND_PLACEHOLDER_0x1f = 0x1f;
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.17;
                            import {IWETH9} from '../interfaces/external/IWETH9.sol';
                            /// @title Constant state
                            /// @notice Constant state used by the Universal Router
                            library Constants {
                                /// @dev Used for identifying cases when this contract's balance of a token is to be used as an input
                                /// This value is equivalent to 1<<255, i.e. a singular 1 in the most significant bit.
                                uint256 internal constant CONTRACT_BALANCE = 0x8000000000000000000000000000000000000000000000000000000000000000;
                                /// @dev Used for identifying cases when a v2 pair has already received input tokens
                                uint256 internal constant ALREADY_PAID = 0;
                                /// @dev Used as a flag for identifying the transfer of ETH instead of a token
                                address internal constant ETH = address(0);
                                /// @dev Used as a flag for identifying that msg.sender should be used, saves gas by sending more 0 bytes
                                address internal constant MSG_SENDER = address(1);
                                /// @dev Used as a flag for identifying address(this) should be used, saves gas by sending more 0 bytes
                                address internal constant ADDRESS_THIS = address(2);
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.17;
                            import {Constants} from '../libraries/Constants.sol';
                            /// @title Recipient Library
                            /// @notice Calculates the recipient address for a command
                            library Recipient {
                                /// @notice Calculates the recipient address for a command
                                /// @param recipient The recipient or recipient-flag for the command
                                /// @return output The resultant recipient for the command
                                function map(address recipient) internal view returns (address) {
                                    if (recipient == Constants.MSG_SENDER) {
                                        return msg.sender;
                                    } else if (recipient == Constants.ADDRESS_THIS) {
                                        return address(this);
                                    } else {
                                        return recipient;
                                    }
                                }
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.17;
                            import {Constants} from '../libraries/Constants.sol';
                            import {RouterImmutables} from '../base/RouterImmutables.sol';
                            import {SafeTransferLib} from 'solmate/utils/SafeTransferLib.sol';
                            import {ERC20} from 'solmate/tokens/ERC20.sol';
                            import {ERC721} from 'solmate/tokens/ERC721.sol';
                            import {ERC1155} from 'solmate/tokens/ERC1155.sol';
                            /// @title Payments contract
                            /// @notice Performs various operations around the payment of ETH and tokens
                            abstract contract Payments is RouterImmutables {
                                using SafeTransferLib for ERC20;
                                using SafeTransferLib for address;
                                error InsufficientToken();
                                error InsufficientETH();
                                error InvalidBips();
                                uint256 internal constant FEE_BIPS_BASE = 10_000;
                                /// @notice Pays an amount of ETH or ERC20 to a recipient
                                /// @param token The token to pay (can be ETH using Constants.ETH)
                                /// @param recipient The address that will receive the payment
                                /// @param value The amount to pay
                                function pay(address token, address recipient, uint256 value) internal {
                                    if (token == Constants.ETH) {
                                        recipient.safeTransferETH(value);
                                    } else {
                                        if (value == Constants.CONTRACT_BALANCE) {
                                            value = ERC20(token).balanceOf(address(this));
                                        }
                                        ERC20(token).safeTransfer(recipient, value);
                                    }
                                }
                                /// @notice Pays a proportion of the contract's ETH or ERC20 to a recipient
                                /// @param token The token to pay (can be ETH using Constants.ETH)
                                /// @param recipient The address that will receive payment
                                /// @param bips Portion in bips of whole balance of the contract
                                function payPortion(address token, address recipient, uint256 bips) internal {
                                    if (bips == 0 || bips > 10_000) revert InvalidBips();
                                    if (token == Constants.ETH) {
                                        uint256 balance = address(this).balance;
                                        uint256 amount = (balance * bips) / FEE_BIPS_BASE;
                                        recipient.safeTransferETH(amount);
                                    } else {
                                        uint256 balance = ERC20(token).balanceOf(address(this));
                                        uint256 amount = (balance * bips) / FEE_BIPS_BASE;
                                        // pay with tokens already in the contract (for the exact input multihop case)
                                        ERC20(token).safeTransfer(recipient, amount);
                                    }
                                }
                                /// @notice Sweeps all of the contract's ERC20 or ETH to an address
                                /// @param token The token to sweep (can be ETH using Constants.ETH)
                                /// @param recipient The address that will receive payment
                                /// @param amountMinimum The minimum desired amount
                                function sweep(address token, address recipient, uint256 amountMinimum) internal {
                                    uint256 balance;
                                    if (token == Constants.ETH) {
                                        balance = address(this).balance;
                                        if (balance < amountMinimum) revert InsufficientETH();
                                        if (balance > 0) recipient.safeTransferETH(balance);
                                    } else {
                                        balance = ERC20(token).balanceOf(address(this));
                                        if (balance < amountMinimum) revert InsufficientToken();
                                        if (balance > 0) ERC20(token).safeTransfer(recipient, balance);
                                    }
                                }
                                /// @notice Sweeps an ERC721 to a recipient from the contract
                                /// @param token The ERC721 token to sweep
                                /// @param recipient The address that will receive payment
                                /// @param id The ID of the ERC721 to sweep
                                function sweepERC721(address token, address recipient, uint256 id) internal {
                                    ERC721(token).safeTransferFrom(address(this), recipient, id);
                                }
                                /// @notice Sweeps all of the contract's ERC1155 to an address
                                /// @param token The ERC1155 token to sweep
                                /// @param recipient The address that will receive payment
                                /// @param id The ID of the ERC1155 to sweep
                                /// @param amountMinimum The minimum desired amount
                                function sweepERC1155(address token, address recipient, uint256 id, uint256 amountMinimum) internal {
                                    uint256 balance = ERC1155(token).balanceOf(address(this), id);
                                    if (balance < amountMinimum) revert InsufficientToken();
                                    ERC1155(token).safeTransferFrom(address(this), recipient, id, balance, bytes(''));
                                }
                                /// @notice Wraps an amount of ETH into WETH
                                /// @param recipient The recipient of the WETH
                                /// @param amount The amount to wrap (can be CONTRACT_BALANCE)
                                function wrapETH(address recipient, uint256 amount) internal {
                                    if (amount == Constants.CONTRACT_BALANCE) {
                                        amount = address(this).balance;
                                    } else if (amount > address(this).balance) {
                                        revert InsufficientETH();
                                    }
                                    if (amount > 0) {
                                        WETH9.deposit{value: amount}();
                                        WETH9.transfer(recipient, amount);
                                    }
                                }
                                /// @notice Unwraps all of the contract's WETH into ETH
                                /// @param recipient The recipient of the ETH
                                /// @param amountMinimum The minimum amount of ETH desired
                                function unwrapWETH9(address recipient, uint256 amountMinimum) internal {
                                    uint256 value = WETH9.balanceOf(address(this));
                                    if (value < amountMinimum) {
                                        revert InsufficientETH();
                                    }
                                    if (value > 0) {
                                        WETH9.withdraw(value);
                                        recipient.safeTransferETH(value);
                                    }
                                }
                            }
                            pragma solidity ^0.8.17;
                            import {IAllowanceTransfer} from 'permit2/src/interfaces/IAllowanceTransfer.sol';
                            import {SafeCast160} from 'permit2/src/libraries/SafeCast160.sol';
                            import {Payments} from './Payments.sol';
                            import {Constants} from '../libraries/Constants.sol';
                            import {RouterImmutables} from '../base/RouterImmutables.sol';
                            /// @title Payments through Permit2
                            /// @notice Performs interactions with Permit2 to transfer tokens
                            abstract contract Permit2Payments is Payments {
                                using SafeCast160 for uint256;
                                error FromAddressIsNotOwner();
                                /// @notice Performs a transferFrom on Permit2
                                /// @param token The token to transfer
                                /// @param from The address to transfer from
                                /// @param to The recipient of the transfer
                                /// @param amount The amount to transfer
                                function permit2TransferFrom(address token, address from, address to, uint160 amount) internal {
                                    PERMIT2.transferFrom(from, to, amount, token);
                                }
                                /// @notice Performs a batch transferFrom on Permit2
                                /// @param batchDetails An array detailing each of the transfers that should occur
                                function permit2TransferFrom(IAllowanceTransfer.AllowanceTransferDetails[] memory batchDetails) internal {
                                    address owner = msg.sender;
                                    uint256 batchLength = batchDetails.length;
                                    for (uint256 i = 0; i < batchLength; ++i) {
                                        if (batchDetails[i].from != owner) revert FromAddressIsNotOwner();
                                    }
                                    PERMIT2.transferFrom(batchDetails);
                                }
                                /// @notice Either performs a regular payment or transferFrom on Permit2, depending on the payer address
                                /// @param token The token to transfer
                                /// @param payer The address to pay for the transfer
                                /// @param recipient The recipient of the transfer
                                /// @param amount The amount to transfer
                                function payOrPermit2Transfer(address token, address payer, address recipient, uint256 amount) internal {
                                    if (payer == address(this)) pay(token, recipient, amount);
                                    else permit2TransferFrom(token, payer, recipient, amount.toUint160());
                                }
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity >=0.5.0;
                            import {IUniswapV2Pair} from '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
                            /// @title Uniswap v2 Helper Library
                            /// @notice Calculates the recipient address for a command
                            library UniswapV2Library {
                                error InvalidReserves();
                                error InvalidPath();
                                /// @notice Calculates the v2 address for a pair without making any external calls
                                /// @param factory The address of the v2 factory
                                /// @param initCodeHash The hash of the pair initcode
                                /// @param tokenA One of the tokens in the pair
                                /// @param tokenB The other token in the pair
                                /// @return pair The resultant v2 pair address
                                function pairFor(address factory, bytes32 initCodeHash, address tokenA, address tokenB)
                                    internal
                                    pure
                                    returns (address pair)
                                {
                                    (address token0, address token1) = sortTokens(tokenA, tokenB);
                                    pair = pairForPreSorted(factory, initCodeHash, token0, token1);
                                }
                                /// @notice Calculates the v2 address for a pair and the pair's token0
                                /// @param factory The address of the v2 factory
                                /// @param initCodeHash The hash of the pair initcode
                                /// @param tokenA One of the tokens in the pair
                                /// @param tokenB The other token in the pair
                                /// @return pair The resultant v2 pair address
                                /// @return token0 The token considered token0 in this pair
                                function pairAndToken0For(address factory, bytes32 initCodeHash, address tokenA, address tokenB)
                                    internal
                                    pure
                                    returns (address pair, address token0)
                                {
                                    address token1;
                                    (token0, token1) = sortTokens(tokenA, tokenB);
                                    pair = pairForPreSorted(factory, initCodeHash, token0, token1);
                                }
                                /// @notice Calculates the v2 address for a pair assuming the input tokens are pre-sorted
                                /// @param factory The address of the v2 factory
                                /// @param initCodeHash The hash of the pair initcode
                                /// @param token0 The pair's token0
                                /// @param token1 The pair's token1
                                /// @return pair The resultant v2 pair address
                                function pairForPreSorted(address factory, bytes32 initCodeHash, address token0, address token1)
                                    private
                                    pure
                                    returns (address pair)
                                {
                                    pair = address(
                                        uint160(
                                            uint256(
                                                keccak256(
                                                    abi.encodePacked(hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), initCodeHash)
                                                )
                                            )
                                        )
                                    );
                                }
                                /// @notice Calculates the v2 address for a pair and fetches the reserves for each token
                                /// @param factory The address of the v2 factory
                                /// @param initCodeHash The hash of the pair initcode
                                /// @param tokenA One of the tokens in the pair
                                /// @param tokenB The other token in the pair
                                /// @return pair The resultant v2 pair address
                                /// @return reserveA The reserves for tokenA
                                /// @return reserveB The reserves for tokenB
                                function pairAndReservesFor(address factory, bytes32 initCodeHash, address tokenA, address tokenB)
                                    private
                                    view
                                    returns (address pair, uint256 reserveA, uint256 reserveB)
                                {
                                    address token0;
                                    (pair, token0) = pairAndToken0For(factory, initCodeHash, tokenA, tokenB);
                                    (uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(pair).getReserves();
                                    (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
                                }
                                /// @notice Given an input asset amount returns the maximum output amount of the other asset
                                /// @param amountIn The token input amount
                                /// @param reserveIn The reserves available of the input token
                                /// @param reserveOut The reserves available of the output token
                                /// @return amountOut The output amount of the output token
                                function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut)
                                    internal
                                    pure
                                    returns (uint256 amountOut)
                                {
                                    if (reserveIn == 0 || reserveOut == 0) revert InvalidReserves();
                                    uint256 amountInWithFee = amountIn * 997;
                                    uint256 numerator = amountInWithFee * reserveOut;
                                    uint256 denominator = reserveIn * 1000 + amountInWithFee;
                                    amountOut = numerator / denominator;
                                }
                                /// @notice Returns the input amount needed for a desired output amount in a single-hop trade
                                /// @param amountOut The desired output amount
                                /// @param reserveIn The reserves available of the input token
                                /// @param reserveOut The reserves available of the output token
                                /// @return amountIn The input amount of the input token
                                function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut)
                                    internal
                                    pure
                                    returns (uint256 amountIn)
                                {
                                    if (reserveIn == 0 || reserveOut == 0) revert InvalidReserves();
                                    uint256 numerator = reserveIn * amountOut * 1000;
                                    uint256 denominator = (reserveOut - amountOut) * 997;
                                    amountIn = (numerator / denominator) + 1;
                                }
                                /// @notice Returns the input amount needed for a desired output amount in a multi-hop trade
                                /// @param factory The address of the v2 factory
                                /// @param initCodeHash The hash of the pair initcode
                                /// @param amountOut The desired output amount
                                /// @param path The path of the multi-hop trade
                                /// @return amount The input amount of the input token
                                /// @return pair The first pair in the trade
                                function getAmountInMultihop(address factory, bytes32 initCodeHash, uint256 amountOut, address[] memory path)
                                    internal
                                    view
                                    returns (uint256 amount, address pair)
                                {
                                    if (path.length < 2) revert InvalidPath();
                                    amount = amountOut;
                                    for (uint256 i = path.length - 1; i > 0; i--) {
                                        uint256 reserveIn;
                                        uint256 reserveOut;
                                        (pair, reserveIn, reserveOut) = pairAndReservesFor(factory, initCodeHash, path[i - 1], path[i]);
                                        amount = getAmountIn(amount, reserveIn, reserveOut);
                                    }
                                }
                                /// @notice Sorts two tokens to return token0 and token1
                                /// @param tokenA The first token to sort
                                /// @param tokenB The other token to sort
                                /// @return token0 The smaller token by address value
                                /// @return token1 The larger token by address value
                                function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
                                    (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
                                }
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.17;
                            import {IUniswapV2Pair} from '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
                            import {UniswapV2Library} from './UniswapV2Library.sol';
                            import {RouterImmutables} from '../../../base/RouterImmutables.sol';
                            import {Payments} from '../../Payments.sol';
                            import {Permit2Payments} from '../../Permit2Payments.sol';
                            import {Constants} from '../../../libraries/Constants.sol';
                            import {ERC20} from 'solmate/tokens/ERC20.sol';
                            /// @title Router for Uniswap v2 Trades
                            abstract contract V2SwapRouter is RouterImmutables, Permit2Payments {
                                error V2TooLittleReceived();
                                error V2TooMuchRequested();
                                error V2InvalidPath();
                                function _v2Swap(address[] memory path, address recipient, address pair) private {
                                    unchecked {
                                        if (path.length < 2) revert V2InvalidPath();
                                        // cached to save on duplicate operations
                                        (address token0,) = UniswapV2Library.sortTokens(path[0], path[1]);
                                        uint256 finalPairIndex = path.length - 1;
                                        uint256 penultimatePairIndex = finalPairIndex - 1;
                                        for (uint256 i; i < finalPairIndex; i++) {
                                            (address input, address output) = (path[i], path[i + 1]);
                                            (uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(pair).getReserves();
                                            (uint256 reserveInput, uint256 reserveOutput) =
                                                input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
                                            uint256 amountInput = ERC20(input).balanceOf(pair) - reserveInput;
                                            uint256 amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
                                            (uint256 amount0Out, uint256 amount1Out) =
                                                input == token0 ? (uint256(0), amountOutput) : (amountOutput, uint256(0));
                                            address nextPair;
                                            (nextPair, token0) = i < penultimatePairIndex
                                                ? UniswapV2Library.pairAndToken0For(
                                                    UNISWAP_V2_FACTORY, UNISWAP_V2_PAIR_INIT_CODE_HASH, output, path[i + 2]
                                                )
                                                : (recipient, address(0));
                                            IUniswapV2Pair(pair).swap(amount0Out, amount1Out, nextPair, new bytes(0));
                                            pair = nextPair;
                                        }
                                    }
                                }
                                /// @notice Performs a Uniswap v2 exact input swap
                                /// @param recipient The recipient of the output tokens
                                /// @param amountIn The amount of input tokens for the trade
                                /// @param amountOutMinimum The minimum desired amount of output tokens
                                /// @param path The path of the trade as an array of token addresses
                                /// @param payer The address that will be paying the input
                                function v2SwapExactInput(
                                    address recipient,
                                    uint256 amountIn,
                                    uint256 amountOutMinimum,
                                    address[] memory path,
                                    address payer
                                ) internal {
                                    address firstPair =
                                        UniswapV2Library.pairFor(UNISWAP_V2_FACTORY, UNISWAP_V2_PAIR_INIT_CODE_HASH, path[0], path[1]);
                                    if (
                                        amountIn != Constants.ALREADY_PAID // amountIn of 0 to signal that the pair already has the tokens
                                    ) {
                                        payOrPermit2Transfer(path[0], payer, firstPair, amountIn);
                                    }
                                    ERC20 tokenOut = ERC20(path[path.length - 1]);
                                    uint256 balanceBefore = tokenOut.balanceOf(recipient);
                                    _v2Swap(path, recipient, firstPair);
                                    uint256 amountOut = tokenOut.balanceOf(recipient) - balanceBefore;
                                    if (amountOut < amountOutMinimum) revert V2TooLittleReceived();
                                }
                                /// @notice Performs a Uniswap v2 exact output swap
                                /// @param recipient The recipient of the output tokens
                                /// @param amountOut The amount of output tokens to receive for the trade
                                /// @param amountInMaximum The maximum desired amount of input tokens
                                /// @param path The path of the trade as an array of token addresses
                                /// @param payer The address that will be paying the input
                                function v2SwapExactOutput(
                                    address recipient,
                                    uint256 amountOut,
                                    uint256 amountInMaximum,
                                    address[] memory path,
                                    address payer
                                ) internal {
                                    (uint256 amountIn, address firstPair) =
                                        UniswapV2Library.getAmountInMultihop(UNISWAP_V2_FACTORY, UNISWAP_V2_PAIR_INIT_CODE_HASH, amountOut, path);
                                    if (amountIn > amountInMaximum) revert V2TooMuchRequested();
                                    payOrPermit2Transfer(path[0], payer, firstPair, amountIn);
                                    _v2Swap(path, recipient, firstPair);
                                }
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            /// @title Library for Bytes Manipulation
                            /// Based on Gonçalo Sá's BytesLib - but updated and heavily editted
                            pragma solidity ^0.8.0;
                            library BytesLib {
                                error SliceOverflow();
                                error SliceOutOfBounds();
                                error ToAddressOverflow();
                                error ToAddressOutOfBounds();
                                error ToUint24Overflow();
                                error ToUint24OutOfBounds();
                                error NoSlice();
                                // Constants used in slicePool
                                // 43 bytes: token + feeTier + token
                                uint256 internal constant POOL_LENGTH = 43;
                                // Offset from beginning of _bytes to start copying from given that 43 isnt a multiple of 32
                                uint256 internal constant OFFSET = 11; // 43-32=11
                                // Constants used in inPlaceSliceToken
                                uint256 internal constant ADDR_AND_FEE_LENGTH = 23;
                                /// @notice Slices and returns the first 43 bytes from a bytes string
                                /// @dev 43 bytes = pool (20 bytes) + feeTier (3 bytes) + pool (20 bytes)
                                /// @param _bytes The input bytes string
                                /// @return tempBytes The first 43 bytes of the input bytes string
                                function slicePool(bytes memory _bytes) internal pure returns (bytes memory tempBytes) {
                                    if (_bytes.length < POOL_LENGTH) revert SliceOutOfBounds();
                                    assembly ("memory-safe") {
                                        // Get a location of some free memory and store it in tempBytes as
                                        // Solidity does for memory variables.
                                        tempBytes := mload(0x40)
                                        // The first word of the slice result is a partial word read from the
                                        //  original array - given that 43 is not a multiple of 32. To read it,
                                        // we use the length of that partial word (43-32=11) and start copying
                                        // that many bytes into the array. The first word we copy will start
                                        // with data we don't care about, but the last 11 bytes will
                                        // land at the beginning of the contents of the new array. When
                                        // we're done copying, we overwrite the full first word with
                                        // the actual length of the slice.
                                        let copyDestination := add(tempBytes, OFFSET)
                                        let endNewBytes := add(copyDestination, POOL_LENGTH)
                                        let copyFrom := add(_bytes, OFFSET)
                                        mstore(copyDestination, mload(copyFrom))
                                        copyDestination := add(copyDestination, 0x20)
                                        copyFrom := add(copyFrom, 0x20)
                                        mstore(copyDestination, mload(copyFrom))
                                        mstore(tempBytes, POOL_LENGTH)
                                        // update free-memory pointer
                                        // allocating the array padded to 32 bytes like the compiler does now
                                        mstore(0x40, add(tempBytes, 0x60))
                                    }
                                }
                                /// @notice Removes the first 23 bytes of a bytes string in-place
                                /// @dev 23 bytes = pool (20 bytes) + feeTier (3 bytes)
                                /// @param _bytes The input bytes string to slice
                                function inPlaceSliceToken(bytes memory _bytes, uint256 _length) internal pure {
                                    unchecked {
                                        if (_length + 31 < _length) revert SliceOverflow();
                                        if (ADDR_AND_FEE_LENGTH + _length < ADDR_AND_FEE_LENGTH) revert SliceOverflow();
                                        if (_bytes.length < ADDR_AND_FEE_LENGTH + _length) revert SliceOutOfBounds();
                                        if (_length == 0) revert NoSlice();
                                    }
                                    assembly ("memory-safe") {
                                        // The first word of the slice result is potentially a partial
                                        // word read from the original array. To read it, we calculate
                                        // the length of that partial word and start copying that many
                                        // bytes into the array. The first word we copy will start with
                                        // data we don't care about, but the last `lengthmod` bytes will
                                        // land at the beginning of the contents of the new array. When
                                        // we're done copying, we overwrite the full first word with
                                        // the actual length of the slice.
                                        // 31==0b11111 to extract the final 5 bits of the length of the slice - the amount that
                                        // the length in bytes goes over a round number of bytes32
                                        let lengthmod := and(_length, 31)
                                        // The multiplication in the next line is necessary
                                        // because when slicing multiples of 32 bytes (lengthmod == 0)
                                        // the following copy loop was copying the origin's length
                                        // and then ending prematurely not copying everything it should.
                                        // if the _length is not a multiple of 32, offset is lengthmod
                                        // otherwise its 32 (as lengthmod is 0)
                                        // offset from beginning of _bytes to start copying from
                                        let offset := add(lengthmod, mul(0x20, iszero(lengthmod)))
                                        // this does calculates where to start copying bytes into
                                        // bytes is the location where the bytes array is
                                        // byte+offset is the location where copying should start from
                                        let copyDestination := add(_bytes, offset)
                                        let endNewBytes := add(copyDestination, _length)
                                        for { let copyFrom := add(copyDestination, ADDR_AND_FEE_LENGTH) } lt(copyDestination, endNewBytes) {
                                            copyDestination := add(copyDestination, 0x20)
                                            copyFrom := add(copyFrom, 0x20)
                                        } { mstore(copyDestination, mload(copyFrom)) }
                                        mstore(_bytes, _length)
                                    }
                                }
                                /// @notice Returns the address starting at byte `_start`
                                /// @dev _bytesLength must equal _bytes.length for this to function correctly
                                /// @param _bytes The input bytes string to slice
                                /// @param _start The starting index of the address
                                /// @param _bytesLength The length of _bytes
                                /// @return tempAddress The address starting at _start
                                function toAddress(bytes memory _bytes, uint256 _start, uint256 _bytesLength)
                                    internal
                                    pure
                                    returns (address tempAddress)
                                {
                                    unchecked {
                                        if (_start + 20 < _start) revert ToAddressOverflow();
                                        if (_bytesLength < _start + 20) revert ToAddressOutOfBounds();
                                    }
                                    assembly {
                                        tempAddress := mload(add(add(_bytes, 0x14), _start))
                                    }
                                }
                                /// @notice Returns the uint24 starting at byte `_start`
                                /// @dev _bytesLength must equal _bytes.length for this to function correctly
                                /// @param _bytes The input bytes string to slice
                                /// @param _start The starting index of the uint24
                                /// @param _bytesLength The length of _bytes
                                /// @return tempUint24 The uint24 starting at _start
                                function toUint24(bytes memory _bytes, uint256 _start, uint256 _bytesLength)
                                    internal
                                    pure
                                    returns (uint24 tempUint24)
                                {
                                    unchecked {
                                        if (_start + 3 < _start) revert ToUint24Overflow();
                                        if (_bytesLength < _start + 3) revert ToUint24OutOfBounds();
                                    }
                                    assembly {
                                        tempUint24 := mload(add(add(_bytes, 0x3), _start))
                                    }
                                }
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity >=0.6.0;
                            import {BytesLib} from './BytesLib.sol';
                            /// @title Functions for manipulating path data for multihop swaps
                            library V3Path {
                                using BytesLib for bytes;
                                /// @dev The length of the bytes encoded address
                                uint256 private constant ADDR_SIZE = 20;
                                /// @dev The length of the bytes encoded fee
                                uint256 private constant FEE_SIZE = 3;
                                /// @dev The offset of a single token address and pool fee
                                uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
                                /// @dev The offset of an encoded pool key
                                uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
                                /// @dev The minimum length of an encoding that contains 2 or more pools
                                uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;
                                /// @notice Returns true iff the path contains two or more pools
                                /// @param path The encoded swap path
                                /// @return True if path contains two or more pools, otherwise false
                                function hasMultiplePools(bytes memory path) internal pure returns (bool) {
                                    return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
                                }
                                /// @notice Decodes the first pool in path
                                /// @param path The bytes encoded swap path
                                /// @return tokenA The first token of the given pool
                                /// @return tokenB The second token of the given pool
                                /// @return fee The fee level of the pool
                                function decodeFirstPool(bytes memory path) internal pure returns (address tokenA, address tokenB, uint24 fee) {
                                    uint256 bytesLength = path.length;
                                    tokenA = path.toAddress(0, bytesLength);
                                    fee = path.toUint24(ADDR_SIZE, bytesLength);
                                    tokenB = path.toAddress(NEXT_OFFSET, bytesLength);
                                }
                                /// @notice Gets the segment corresponding to the first pool in the path
                                /// @param path The bytes encoded swap path
                                /// @return The segment containing all data necessary to target the first pool in the path
                                function getFirstPool(bytes memory path) internal pure returns (bytes memory) {
                                    return path.slicePool();
                                }
                                function decodeFirstToken(bytes memory path) internal pure returns (address tokenA) {
                                    tokenA = path.toAddress(0, path.length);
                                }
                                /// @notice Skips a token + fee element from the buffer in place
                                /// @param path The swap path
                                function skipToken(bytes memory path) internal pure {
                                    path.inPlaceSliceToken(path.length - NEXT_OFFSET);
                                }
                            }
                            // SPDX-License-Identifier: GPL-3.0-or-later
                            pragma solidity ^0.8.17;
                            import {V3Path} from './V3Path.sol';
                            import {SafeCast} from '@uniswap/v3-core/contracts/libraries/SafeCast.sol';
                            import {IUniswapV3Pool} from '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
                            import {IUniswapV3SwapCallback} from '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
                            import {Constants} from '../../../libraries/Constants.sol';
                            import {RouterImmutables} from '../../../base/RouterImmutables.sol';
                            import {Permit2Payments} from '../../Permit2Payments.sol';
                            import {Constants} from '../../../libraries/Constants.sol';
                            import {ERC20} from 'solmate/tokens/ERC20.sol';
                            /// @title Router for Uniswap v3 Trades
                            abstract contract V3SwapRouter is RouterImmutables, Permit2Payments, IUniswapV3SwapCallback {
                                using V3Path for bytes;
                                using SafeCast for uint256;
                                error V3InvalidSwap();
                                error V3TooLittleReceived();
                                error V3TooMuchRequested();
                                error V3InvalidAmountOut();
                                error V3InvalidCaller();
                                /// @dev Used as the placeholder value for maxAmountIn, because the computed amount in for an exact output swap
                                /// can never actually be this value
                                uint256 private constant DEFAULT_MAX_AMOUNT_IN = type(uint256).max;
                                /// @dev Transient storage variable used for checking slippage
                                uint256 private maxAmountInCached = DEFAULT_MAX_AMOUNT_IN;
                                /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
                                uint160 internal constant MIN_SQRT_RATIO = 4295128739;
                                /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
                                uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
                                function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external {
                                    if (amount0Delta <= 0 && amount1Delta <= 0) revert V3InvalidSwap(); // swaps entirely within 0-liquidity regions are not supported
                                    (bytes memory path, address payer) = abi.decode(data, (bytes, address));
                                    // because exact output swaps are executed in reverse order, in this case tokenOut is actually tokenIn
                                    (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
                                    if (computePoolAddress(tokenIn, tokenOut, fee) != msg.sender) revert V3InvalidCaller();
                                    (bool isExactInput, uint256 amountToPay) =
                                        amount0Delta > 0 ? (tokenIn < tokenOut, uint256(amount0Delta)) : (tokenOut < tokenIn, uint256(amount1Delta));
                                    if (isExactInput) {
                                        // Pay the pool (msg.sender)
                                        payOrPermit2Transfer(tokenIn, payer, msg.sender, amountToPay);
                                    } else {
                                        // either initiate the next swap or pay
                                        if (path.hasMultiplePools()) {
                                            // this is an intermediate step so the payer is actually this contract
                                            path.skipToken();
                                            _swap(-amountToPay.toInt256(), msg.sender, path, payer, false);
                                        } else {
                                            if (amountToPay > maxAmountInCached) revert V3TooMuchRequested();
                                            // note that because exact output swaps are executed in reverse order, tokenOut is actually tokenIn
                                            payOrPermit2Transfer(tokenOut, payer, msg.sender, amountToPay);
                                        }
                                    }
                                }
                                /// @notice Performs a Uniswap v3 exact input swap
                                /// @param recipient The recipient of the output tokens
                                /// @param amountIn The amount of input tokens for the trade
                                /// @param amountOutMinimum The minimum desired amount of output tokens
                                /// @param path The path of the trade as a bytes string
                                /// @param payer The address that will be paying the input
                                function v3SwapExactInput(
                                    address recipient,
                                    uint256 amountIn,
                                    uint256 amountOutMinimum,
                                    bytes memory path,
                                    address payer
                                ) internal {
                                    // use amountIn == Constants.CONTRACT_BALANCE as a flag to swap the entire balance of the contract
                                    if (amountIn == Constants.CONTRACT_BALANCE) {
                                        address tokenIn = path.decodeFirstToken();
                                        amountIn = ERC20(tokenIn).balanceOf(address(this));
                                    }
                                    uint256 amountOut;
                                    while (true) {
                                        bool hasMultiplePools = path.hasMultiplePools();
                                        // the outputs of prior swaps become the inputs to subsequent ones
                                        (int256 amount0Delta, int256 amount1Delta, bool zeroForOne) = _swap(
                                            amountIn.toInt256(),
                                            hasMultiplePools ? address(this) : recipient, // for intermediate swaps, this contract custodies
                                            path.getFirstPool(), // only the first pool is needed
                                            payer, // for intermediate swaps, this contract custodies
                                            true
                                        );
                                        amountIn = uint256(-(zeroForOne ? amount1Delta : amount0Delta));
                                        // decide whether to continue or terminate
                                        if (hasMultiplePools) {
                                            payer = address(this);
                                            path.skipToken();
                                        } else {
                                            amountOut = amountIn;
                                            break;
                                        }
                                    }
                                    if (amountOut < amountOutMinimum) revert V3TooLittleReceived();
                                }
                                /// @notice Performs a Uniswap v3 exact output swap
                                /// @param recipient The recipient of the output tokens
                                /// @param amountOut The amount of output tokens to receive for the trade
                                /// @param amountInMaximum The maximum desired amount of input tokens
                                /// @param path The path of the trade as a bytes string
                                /// @param payer The address that will be paying the input
                                function v3SwapExactOutput(
                                    address recipient,
                                    uint256 amountOut,
                                    uint256 amountInMaximum,
                                    bytes memory path,
                                    address payer
                                ) internal {
                                    maxAmountInCached = amountInMaximum;
                                    (int256 amount0Delta, int256 amount1Delta, bool zeroForOne) =
                                        _swap(-amountOut.toInt256(), recipient, path, payer, false);
                                    uint256 amountOutReceived = zeroForOne ? uint256(-amount1Delta) : uint256(-amount0Delta);
                                    if (amountOutReceived != amountOut) revert V3InvalidAmountOut();
                                    maxAmountInCached = DEFAULT_MAX_AMOUNT_IN;
                                }
                                /// @dev Performs a single swap for both exactIn and exactOut
                                /// For exactIn, `amount` is `amountIn`. For exactOut, `amount` is `-amountOut`
                                function _swap(int256 amount, address recipient, bytes memory path, address payer, bool isExactIn)
                                    private
                                    returns (int256 amount0Delta, int256 amount1Delta, bool zeroForOne)
                                {
                                    (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
                                    zeroForOne = isExactIn ? tokenIn < tokenOut : tokenOut < tokenIn;
                                    (amount0Delta, amount1Delta) = IUniswapV3Pool(computePoolAddress(tokenIn, tokenOut, fee)).swap(
                                        recipient,
                                        zeroForOne,
                                        amount,
                                        (zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1),
                                        abi.encode(path, payer)
                                    );
                                }
                                function computePoolAddress(address tokenA, address tokenB, uint24 fee) private view returns (address pool) {
                                    if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
                                    pool = address(
                                        uint160(
                                            uint256(
                                                keccak256(
                                                    abi.encodePacked(
                                                        hex'ff',
                                                        UNISWAP_V3_FACTORY,
                                                        keccak256(abi.encode(tokenA, tokenB, fee)),
                                                        UNISWAP_V3_POOL_INIT_CODE_HASH
                                                    )
                                                )
                                            )
                                        )
                                    );
                                }
                            }
                            // SPDX-License-Identifier: MIT
                            // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
                            pragma solidity ^0.8.0;
                            import "../../utils/introspection/IERC165.sol";
                            /**
                             * @dev _Available since v3.1._
                             */
                            interface IERC1155Receiver is IERC165 {
                                /**
                                 * @dev Handles the receipt of a single ERC1155 token type. This function is
                                 * called at the end of a `safeTransferFrom` after the balance has been updated.
                                 *
                                 * NOTE: To accept the transfer, this must return
                                 * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
                                 * (i.e. 0xf23a6e61, or its own function selector).
                                 *
                                 * @param operator The address which initiated the transfer (i.e. msg.sender)
                                 * @param from The address which previously owned the token
                                 * @param id The ID of the token being transferred
                                 * @param value The amount of tokens being transferred
                                 * @param data Additional data with no specified format
                                 * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
                                 */
                                function onERC1155Received(
                                    address operator,
                                    address from,
                                    uint256 id,
                                    uint256 value,
                                    bytes calldata data
                                ) external returns (bytes4);
                                /**
                                 * @dev Handles the receipt of a multiple ERC1155 token types. This function
                                 * is called at the end of a `safeBatchTransferFrom` after the balances have
                                 * been updated.
                                 *
                                 * NOTE: To accept the transfer(s), this must return
                                 * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
                                 * (i.e. 0xbc197c81, or its own function selector).
                                 *
                                 * @param operator The address which initiated the batch transfer (i.e. msg.sender)
                                 * @param from The address which previously owned the token
                                 * @param ids An array containing ids of each token being transferred (order and length must match values array)
                                 * @param values An array containing amounts of each token being transferred (order and length must match ids array)
                                 * @param data Additional data with no specified format
                                 * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
                                 */
                                function onERC1155BatchReceived(
                                    address operator,
                                    address from,
                                    uint256[] calldata ids,
                                    uint256[] calldata values,
                                    bytes calldata data
                                ) external returns (bytes4);
                            }
                            // 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 (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
                            pragma solidity ^0.8.0;
                            /**
                             * @title ERC721 token receiver interface
                             * @dev Interface for any contract that wants to support safeTransfers
                             * from ERC721 asset contracts.
                             */
                            interface IERC721Receiver {
                                /**
                                 * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
                                 * by `operator` from `from`, this function is called.
                                 *
                                 * It must return its Solidity selector to confirm the token transfer.
                                 * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
                                 *
                                 * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
                                 */
                                function onERC721Received(
                                    address operator,
                                    address from,
                                    uint256 tokenId,
                                    bytes calldata data
                                ) external returns (bytes4);
                            }
                            // SPDX-License-Identifier: MIT
                            // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
                            pragma solidity ^0.8.0;
                            /**
                             * @dev Interface of the ERC165 standard, as defined in the
                             * https://eips.ethereum.org/EIPS/eip-165[EIP].
                             *
                             * Implementers can declare support of contract interfaces, which can then be
                             * queried by others ({ERC165Checker}).
                             *
                             * For an implementation, see {ERC165}.
                             */
                            interface IERC165 {
                                /**
                                 * @dev Returns true if this contract implements the interface defined by
                                 * `interfaceId`. See the corresponding
                                 * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
                                 * to learn more about how these ids are created.
                                 *
                                 * This function call must use less than 30 000 gas.
                                 */
                                function supportsInterface(bytes4 interfaceId) external view returns (bool);
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity ^0.8.17;
                            /// @title AllowanceTransfer
                            /// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
                            /// @dev Requires user's token approval on the Permit2 contract
                            interface IAllowanceTransfer {
                                /// @notice Thrown when an allowance on a token has expired.
                                /// @param deadline The timestamp at which the allowed amount is no longer valid
                                error AllowanceExpired(uint256 deadline);
                                /// @notice Thrown when an allowance on a token has been depleted.
                                /// @param amount The maximum amount allowed
                                error InsufficientAllowance(uint256 amount);
                                /// @notice Thrown when too many nonces are invalidated.
                                error ExcessiveInvalidation();
                                /// @notice Emits an event when the owner successfully invalidates an ordered nonce.
                                event NonceInvalidation(
                                    address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
                                );
                                /// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
                                event Approval(
                                    address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
                                );
                                /// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
                                event Permit(
                                    address indexed owner,
                                    address indexed token,
                                    address indexed spender,
                                    uint160 amount,
                                    uint48 expiration,
                                    uint48 nonce
                                );
                                /// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
                                event Lockdown(address indexed owner, address token, address spender);
                                /// @notice The permit data for a token
                                struct PermitDetails {
                                    // ERC20 token address
                                    address token;
                                    // the maximum amount allowed to spend
                                    uint160 amount;
                                    // timestamp at which a spender's token allowances become invalid
                                    uint48 expiration;
                                    // an incrementing value indexed per owner,token,and spender for each signature
                                    uint48 nonce;
                                }
                                /// @notice The permit message signed for a single token allownce
                                struct PermitSingle {
                                    // the permit data for a single token alownce
                                    PermitDetails details;
                                    // address permissioned on the allowed tokens
                                    address spender;
                                    // deadline on the permit signature
                                    uint256 sigDeadline;
                                }
                                /// @notice The permit message signed for multiple token allowances
                                struct PermitBatch {
                                    // the permit data for multiple token allowances
                                    PermitDetails[] details;
                                    // address permissioned on the allowed tokens
                                    address spender;
                                    // deadline on the permit signature
                                    uint256 sigDeadline;
                                }
                                /// @notice The saved permissions
                                /// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
                                /// @dev Setting amount to type(uint160).max sets an unlimited approval
                                struct PackedAllowance {
                                    // amount allowed
                                    uint160 amount;
                                    // permission expiry
                                    uint48 expiration;
                                    // an incrementing value indexed per owner,token,and spender for each signature
                                    uint48 nonce;
                                }
                                /// @notice A token spender pair.
                                struct TokenSpenderPair {
                                    // the token the spender is approved
                                    address token;
                                    // the spender address
                                    address spender;
                                }
                                /// @notice Details for a token transfer.
                                struct AllowanceTransferDetails {
                                    // the owner of the token
                                    address from;
                                    // the recipient of the token
                                    address to;
                                    // the amount of the token
                                    uint160 amount;
                                    // the token to be transferred
                                    address token;
                                }
                                /// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
                                /// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
                                /// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
                                function allowance(address, address, address) external view returns (uint160, uint48, uint48);
                                /// @notice Approves the spender to use up to amount of the specified token up until the expiration
                                /// @param token The token to approve
                                /// @param spender The spender address to approve
                                /// @param amount The approved amount of the token
                                /// @param expiration The timestamp at which the approval is no longer valid
                                /// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
                                /// @dev Setting amount to type(uint160).max sets an unlimited approval
                                function approve(address token, address spender, uint160 amount, uint48 expiration) external;
                                /// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
                                /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
                                /// @param owner The owner of the tokens being approved
                                /// @param permitSingle Data signed over by the owner specifying the terms of approval
                                /// @param signature The owner's signature over the permit data
                                function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;
                                /// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
                                /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
                                /// @param owner The owner of the tokens being approved
                                /// @param permitBatch Data signed over by the owner specifying the terms of approval
                                /// @param signature The owner's signature over the permit data
                                function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;
                                /// @notice Transfer approved tokens from one address to another
                                /// @param from The address to transfer from
                                /// @param to The address of the recipient
                                /// @param amount The amount of the token to transfer
                                /// @param token The token address to transfer
                                /// @dev Requires the from address to have approved at least the desired amount
                                /// of tokens to msg.sender.
                                function transferFrom(address from, address to, uint160 amount, address token) external;
                                /// @notice Transfer approved tokens in a batch
                                /// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
                                /// @dev Requires the from addresses to have approved at least the desired amount
                                /// of tokens to msg.sender.
                                function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;
                                /// @notice Enables performing a "lockdown" of the sender's Permit2 identity
                                /// by batch revoking approvals
                                /// @param approvals Array of approvals to revoke.
                                function lockdown(TokenSpenderPair[] calldata approvals) external;
                                /// @notice Invalidate nonces for a given (token, spender) pair
                                /// @param token The token to invalidate nonces for
                                /// @param spender The spender to invalidate nonces for
                                /// @param newNonce The new nonce to set. Invalidates all nonces less than it.
                                /// @dev Can't invalidate more than 2**16 nonces per transaction.
                                function invalidateNonces(address token, address spender, uint48 newNonce) external;
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity ^0.8.17;
                            library SafeCast160 {
                                /// @notice Thrown when a valude greater than type(uint160).max is cast to uint160
                                error UnsafeCast();
                                /// @notice Safely casts uint256 to uint160
                                /// @param value The uint256 to be cast
                                function toUint160(uint256 value) internal pure returns (uint160) {
                                    if (value > type(uint160).max) revert UnsafeCast();
                                    return uint160(value);
                                }
                            }
                            // SPDX-License-Identifier: AGPL-3.0-only
                            pragma solidity >=0.8.0;
                            /// @notice Minimalist and gas efficient standard ERC1155 implementation.
                            /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC1155.sol)
                            abstract contract ERC1155 {
                                /*//////////////////////////////////////////////////////////////
                                                             EVENTS
                                //////////////////////////////////////////////////////////////*/
                                event TransferSingle(
                                    address indexed operator,
                                    address indexed from,
                                    address indexed to,
                                    uint256 id,
                                    uint256 amount
                                );
                                event TransferBatch(
                                    address indexed operator,
                                    address indexed from,
                                    address indexed to,
                                    uint256[] ids,
                                    uint256[] amounts
                                );
                                event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
                                event URI(string value, uint256 indexed id);
                                /*//////////////////////////////////////////////////////////////
                                                         ERC1155 STORAGE
                                //////////////////////////////////////////////////////////////*/
                                mapping(address => mapping(uint256 => uint256)) public balanceOf;
                                mapping(address => mapping(address => bool)) public isApprovedForAll;
                                /*//////////////////////////////////////////////////////////////
                                                         METADATA LOGIC
                                //////////////////////////////////////////////////////////////*/
                                function uri(uint256 id) public view virtual returns (string memory);
                                /*//////////////////////////////////////////////////////////////
                                                          ERC1155 LOGIC
                                //////////////////////////////////////////////////////////////*/
                                function setApprovalForAll(address operator, bool approved) public virtual {
                                    isApprovedForAll[msg.sender][operator] = approved;
                                    emit ApprovalForAll(msg.sender, operator, approved);
                                }
                                function safeTransferFrom(
                                    address from,
                                    address to,
                                    uint256 id,
                                    uint256 amount,
                                    bytes calldata data
                                ) public virtual {
                                    require(msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED");
                                    balanceOf[from][id] -= amount;
                                    balanceOf[to][id] += amount;
                                    emit TransferSingle(msg.sender, from, to, id, amount);
                                    require(
                                        to.code.length == 0
                                            ? to != address(0)
                                            : ERC1155TokenReceiver(to).onERC1155Received(msg.sender, from, id, amount, data) ==
                                                ERC1155TokenReceiver.onERC1155Received.selector,
                                        "UNSAFE_RECIPIENT"
                                    );
                                }
                                function safeBatchTransferFrom(
                                    address from,
                                    address to,
                                    uint256[] calldata ids,
                                    uint256[] calldata amounts,
                                    bytes calldata data
                                ) public virtual {
                                    require(ids.length == amounts.length, "LENGTH_MISMATCH");
                                    require(msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED");
                                    // Storing these outside the loop saves ~15 gas per iteration.
                                    uint256 id;
                                    uint256 amount;
                                    for (uint256 i = 0; i < ids.length; ) {
                                        id = ids[i];
                                        amount = amounts[i];
                                        balanceOf[from][id] -= amount;
                                        balanceOf[to][id] += amount;
                                        // An array can't have a total length
                                        // larger than the max uint256 value.
                                        unchecked {
                                            ++i;
                                        }
                                    }
                                    emit TransferBatch(msg.sender, from, to, ids, amounts);
                                    require(
                                        to.code.length == 0
                                            ? to != address(0)
                                            : ERC1155TokenReceiver(to).onERC1155BatchReceived(msg.sender, from, ids, amounts, data) ==
                                                ERC1155TokenReceiver.onERC1155BatchReceived.selector,
                                        "UNSAFE_RECIPIENT"
                                    );
                                }
                                function balanceOfBatch(address[] calldata owners, uint256[] calldata ids)
                                    public
                                    view
                                    virtual
                                    returns (uint256[] memory balances)
                                {
                                    require(owners.length == ids.length, "LENGTH_MISMATCH");
                                    balances = new uint256[](owners.length);
                                    // Unchecked because the only math done is incrementing
                                    // the array index counter which cannot possibly overflow.
                                    unchecked {
                                        for (uint256 i = 0; i < owners.length; ++i) {
                                            balances[i] = balanceOf[owners[i]][ids[i]];
                                        }
                                    }
                                }
                                /*//////////////////////////////////////////////////////////////
                                                          ERC165 LOGIC
                                //////////////////////////////////////////////////////////////*/
                                function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
                                    return
                                        interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
                                        interfaceId == 0xd9b67a26 || // ERC165 Interface ID for ERC1155
                                        interfaceId == 0x0e89341c; // ERC165 Interface ID for ERC1155MetadataURI
                                }
                                /*//////////////////////////////////////////////////////////////
                                                    INTERNAL MINT/BURN LOGIC
                                //////////////////////////////////////////////////////////////*/
                                function _mint(
                                    address to,
                                    uint256 id,
                                    uint256 amount,
                                    bytes memory data
                                ) internal virtual {
                                    balanceOf[to][id] += amount;
                                    emit TransferSingle(msg.sender, address(0), to, id, amount);
                                    require(
                                        to.code.length == 0
                                            ? to != address(0)
                                            : ERC1155TokenReceiver(to).onERC1155Received(msg.sender, address(0), id, amount, data) ==
                                                ERC1155TokenReceiver.onERC1155Received.selector,
                                        "UNSAFE_RECIPIENT"
                                    );
                                }
                                function _batchMint(
                                    address to,
                                    uint256[] memory ids,
                                    uint256[] memory amounts,
                                    bytes memory data
                                ) internal virtual {
                                    uint256 idsLength = ids.length; // Saves MLOADs.
                                    require(idsLength == amounts.length, "LENGTH_MISMATCH");
                                    for (uint256 i = 0; i < idsLength; ) {
                                        balanceOf[to][ids[i]] += amounts[i];
                                        // An array can't have a total length
                                        // larger than the max uint256 value.
                                        unchecked {
                                            ++i;
                                        }
                                    }
                                    emit TransferBatch(msg.sender, address(0), to, ids, amounts);
                                    require(
                                        to.code.length == 0
                                            ? to != address(0)
                                            : ERC1155TokenReceiver(to).onERC1155BatchReceived(msg.sender, address(0), ids, amounts, data) ==
                                                ERC1155TokenReceiver.onERC1155BatchReceived.selector,
                                        "UNSAFE_RECIPIENT"
                                    );
                                }
                                function _batchBurn(
                                    address from,
                                    uint256[] memory ids,
                                    uint256[] memory amounts
                                ) internal virtual {
                                    uint256 idsLength = ids.length; // Saves MLOADs.
                                    require(idsLength == amounts.length, "LENGTH_MISMATCH");
                                    for (uint256 i = 0; i < idsLength; ) {
                                        balanceOf[from][ids[i]] -= amounts[i];
                                        // An array can't have a total length
                                        // larger than the max uint256 value.
                                        unchecked {
                                            ++i;
                                        }
                                    }
                                    emit TransferBatch(msg.sender, from, address(0), ids, amounts);
                                }
                                function _burn(
                                    address from,
                                    uint256 id,
                                    uint256 amount
                                ) internal virtual {
                                    balanceOf[from][id] -= amount;
                                    emit TransferSingle(msg.sender, from, address(0), id, amount);
                                }
                            }
                            /// @notice A generic interface for a contract which properly accepts ERC1155 tokens.
                            /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC1155.sol)
                            abstract contract ERC1155TokenReceiver {
                                function onERC1155Received(
                                    address,
                                    address,
                                    uint256,
                                    uint256,
                                    bytes calldata
                                ) external virtual returns (bytes4) {
                                    return ERC1155TokenReceiver.onERC1155Received.selector;
                                }
                                function onERC1155BatchReceived(
                                    address,
                                    address,
                                    uint256[] calldata,
                                    uint256[] calldata,
                                    bytes calldata
                                ) external virtual returns (bytes4) {
                                    return ERC1155TokenReceiver.onERC1155BatchReceived.selector;
                                }
                            }
                            // SPDX-License-Identifier: AGPL-3.0-only
                            pragma solidity >=0.8.0;
                            /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
                            /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
                            /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
                            /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
                            abstract contract ERC20 {
                                /*//////////////////////////////////////////////////////////////
                                                             EVENTS
                                //////////////////////////////////////////////////////////////*/
                                event Transfer(address indexed from, address indexed to, uint256 amount);
                                event Approval(address indexed owner, address indexed spender, uint256 amount);
                                /*//////////////////////////////////////////////////////////////
                                                        METADATA STORAGE
                                //////////////////////////////////////////////////////////////*/
                                string public name;
                                string public symbol;
                                uint8 public immutable decimals;
                                /*//////////////////////////////////////////////////////////////
                                                          ERC20 STORAGE
                                //////////////////////////////////////////////////////////////*/
                                uint256 public totalSupply;
                                mapping(address => uint256) public balanceOf;
                                mapping(address => mapping(address => uint256)) public allowance;
                                /*//////////////////////////////////////////////////////////////
                                                        EIP-2612 STORAGE
                                //////////////////////////////////////////////////////////////*/
                                uint256 internal immutable INITIAL_CHAIN_ID;
                                bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
                                mapping(address => uint256) public nonces;
                                /*//////////////////////////////////////////////////////////////
                                                           CONSTRUCTOR
                                //////////////////////////////////////////////////////////////*/
                                constructor(
                                    string memory _name,
                                    string memory _symbol,
                                    uint8 _decimals
                                ) {
                                    name = _name;
                                    symbol = _symbol;
                                    decimals = _decimals;
                                    INITIAL_CHAIN_ID = block.chainid;
                                    INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
                                }
                                /*//////////////////////////////////////////////////////////////
                                                           ERC20 LOGIC
                                //////////////////////////////////////////////////////////////*/
                                function approve(address spender, uint256 amount) public virtual returns (bool) {
                                    allowance[msg.sender][spender] = amount;
                                    emit Approval(msg.sender, spender, amount);
                                    return true;
                                }
                                function transfer(address to, uint256 amount) public virtual returns (bool) {
                                    balanceOf[msg.sender] -= amount;
                                    // Cannot overflow because the sum of all user
                                    // balances can't exceed the max uint256 value.
                                    unchecked {
                                        balanceOf[to] += amount;
                                    }
                                    emit Transfer(msg.sender, to, amount);
                                    return true;
                                }
                                function transferFrom(
                                    address from,
                                    address to,
                                    uint256 amount
                                ) public virtual returns (bool) {
                                    uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
                                    if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
                                    balanceOf[from] -= amount;
                                    // Cannot overflow because the sum of all user
                                    // balances can't exceed the max uint256 value.
                                    unchecked {
                                        balanceOf[to] += amount;
                                    }
                                    emit Transfer(from, to, amount);
                                    return true;
                                }
                                /*//////////////////////////////////////////////////////////////
                                                         EIP-2612 LOGIC
                                //////////////////////////////////////////////////////////////*/
                                function permit(
                                    address owner,
                                    address spender,
                                    uint256 value,
                                    uint256 deadline,
                                    uint8 v,
                                    bytes32 r,
                                    bytes32 s
                                ) public virtual {
                                    require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
                                    // Unchecked because the only math done is incrementing
                                    // the owner's nonce which cannot realistically overflow.
                                    unchecked {
                                        address recoveredAddress = ecrecover(
                                            keccak256(
                                                abi.encodePacked(
                                                    "\\x19\\x01",
                                                    DOMAIN_SEPARATOR(),
                                                    keccak256(
                                                        abi.encode(
                                                            keccak256(
                                                                "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                                            ),
                                                            owner,
                                                            spender,
                                                            value,
                                                            nonces[owner]++,
                                                            deadline
                                                        )
                                                    )
                                                )
                                            ),
                                            v,
                                            r,
                                            s
                                        );
                                        require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
                                        allowance[recoveredAddress][spender] = value;
                                    }
                                    emit Approval(owner, spender, value);
                                }
                                function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
                                    return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
                                }
                                function computeDomainSeparator() internal view virtual returns (bytes32) {
                                    return
                                        keccak256(
                                            abi.encode(
                                                keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                                keccak256(bytes(name)),
                                                keccak256("1"),
                                                block.chainid,
                                                address(this)
                                            )
                                        );
                                }
                                /*//////////////////////////////////////////////////////////////
                                                    INTERNAL MINT/BURN LOGIC
                                //////////////////////////////////////////////////////////////*/
                                function _mint(address to, uint256 amount) internal virtual {
                                    totalSupply += amount;
                                    // Cannot overflow because the sum of all user
                                    // balances can't exceed the max uint256 value.
                                    unchecked {
                                        balanceOf[to] += amount;
                                    }
                                    emit Transfer(address(0), to, amount);
                                }
                                function _burn(address from, uint256 amount) internal virtual {
                                    balanceOf[from] -= amount;
                                    // Cannot underflow because a user's balance
                                    // will never be larger than the total supply.
                                    unchecked {
                                        totalSupply -= amount;
                                    }
                                    emit Transfer(from, address(0), amount);
                                }
                            }
                            // SPDX-License-Identifier: AGPL-3.0-only
                            pragma solidity >=0.8.0;
                            /// @notice Modern, minimalist, and gas efficient ERC-721 implementation.
                            /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)
                            abstract contract ERC721 {
                                /*//////////////////////////////////////////////////////////////
                                                             EVENTS
                                //////////////////////////////////////////////////////////////*/
                                event Transfer(address indexed from, address indexed to, uint256 indexed id);
                                event Approval(address indexed owner, address indexed spender, uint256 indexed id);
                                event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
                                /*//////////////////////////////////////////////////////////////
                                                     METADATA STORAGE/LOGIC
                                //////////////////////////////////////////////////////////////*/
                                string public name;
                                string public symbol;
                                function tokenURI(uint256 id) public view virtual returns (string memory);
                                /*//////////////////////////////////////////////////////////////
                                                  ERC721 BALANCE/OWNER STORAGE
                                //////////////////////////////////////////////////////////////*/
                                mapping(uint256 => address) internal _ownerOf;
                                mapping(address => uint256) internal _balanceOf;
                                function ownerOf(uint256 id) public view virtual returns (address owner) {
                                    require((owner = _ownerOf[id]) != address(0), "NOT_MINTED");
                                }
                                function balanceOf(address owner) public view virtual returns (uint256) {
                                    require(owner != address(0), "ZERO_ADDRESS");
                                    return _balanceOf[owner];
                                }
                                /*//////////////////////////////////////////////////////////////
                                                     ERC721 APPROVAL STORAGE
                                //////////////////////////////////////////////////////////////*/
                                mapping(uint256 => address) public getApproved;
                                mapping(address => mapping(address => bool)) public isApprovedForAll;
                                /*//////////////////////////////////////////////////////////////
                                                           CONSTRUCTOR
                                //////////////////////////////////////////////////////////////*/
                                constructor(string memory _name, string memory _symbol) {
                                    name = _name;
                                    symbol = _symbol;
                                }
                                /*//////////////////////////////////////////////////////////////
                                                          ERC721 LOGIC
                                //////////////////////////////////////////////////////////////*/
                                function approve(address spender, uint256 id) public virtual {
                                    address owner = _ownerOf[id];
                                    require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED");
                                    getApproved[id] = spender;
                                    emit Approval(owner, spender, id);
                                }
                                function setApprovalForAll(address operator, bool approved) public virtual {
                                    isApprovedForAll[msg.sender][operator] = approved;
                                    emit ApprovalForAll(msg.sender, operator, approved);
                                }
                                function transferFrom(
                                    address from,
                                    address to,
                                    uint256 id
                                ) public virtual {
                                    require(from == _ownerOf[id], "WRONG_FROM");
                                    require(to != address(0), "INVALID_RECIPIENT");
                                    require(
                                        msg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id],
                                        "NOT_AUTHORIZED"
                                    );
                                    // Underflow of the sender's balance is impossible because we check for
                                    // ownership above and the recipient's balance can't realistically overflow.
                                    unchecked {
                                        _balanceOf[from]--;
                                        _balanceOf[to]++;
                                    }
                                    _ownerOf[id] = to;
                                    delete getApproved[id];
                                    emit Transfer(from, to, id);
                                }
                                function safeTransferFrom(
                                    address from,
                                    address to,
                                    uint256 id
                                ) public virtual {
                                    transferFrom(from, to, id);
                                    require(
                                        to.code.length == 0 ||
                                            ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") ==
                                            ERC721TokenReceiver.onERC721Received.selector,
                                        "UNSAFE_RECIPIENT"
                                    );
                                }
                                function safeTransferFrom(
                                    address from,
                                    address to,
                                    uint256 id,
                                    bytes calldata data
                                ) public virtual {
                                    transferFrom(from, to, id);
                                    require(
                                        to.code.length == 0 ||
                                            ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) ==
                                            ERC721TokenReceiver.onERC721Received.selector,
                                        "UNSAFE_RECIPIENT"
                                    );
                                }
                                /*//////////////////////////////////////////////////////////////
                                                          ERC165 LOGIC
                                //////////////////////////////////////////////////////////////*/
                                function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
                                    return
                                        interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
                                        interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721
                                        interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata
                                }
                                /*//////////////////////////////////////////////////////////////
                                                    INTERNAL MINT/BURN LOGIC
                                //////////////////////////////////////////////////////////////*/
                                function _mint(address to, uint256 id) internal virtual {
                                    require(to != address(0), "INVALID_RECIPIENT");
                                    require(_ownerOf[id] == address(0), "ALREADY_MINTED");
                                    // Counter overflow is incredibly unrealistic.
                                    unchecked {
                                        _balanceOf[to]++;
                                    }
                                    _ownerOf[id] = to;
                                    emit Transfer(address(0), to, id);
                                }
                                function _burn(uint256 id) internal virtual {
                                    address owner = _ownerOf[id];
                                    require(owner != address(0), "NOT_MINTED");
                                    // Ownership check above ensures no underflow.
                                    unchecked {
                                        _balanceOf[owner]--;
                                    }
                                    delete _ownerOf[id];
                                    delete getApproved[id];
                                    emit Transfer(owner, address(0), id);
                                }
                                /*//////////////////////////////////////////////////////////////
                                                    INTERNAL SAFE MINT LOGIC
                                //////////////////////////////////////////////////////////////*/
                                function _safeMint(address to, uint256 id) internal virtual {
                                    _mint(to, id);
                                    require(
                                        to.code.length == 0 ||
                                            ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, "") ==
                                            ERC721TokenReceiver.onERC721Received.selector,
                                        "UNSAFE_RECIPIENT"
                                    );
                                }
                                function _safeMint(
                                    address to,
                                    uint256 id,
                                    bytes memory data
                                ) internal virtual {
                                    _mint(to, id);
                                    require(
                                        to.code.length == 0 ||
                                            ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data) ==
                                            ERC721TokenReceiver.onERC721Received.selector,
                                        "UNSAFE_RECIPIENT"
                                    );
                                }
                            }
                            /// @notice A generic interface for a contract which properly accepts ERC721 tokens.
                            /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)
                            abstract contract ERC721TokenReceiver {
                                function onERC721Received(
                                    address,
                                    address,
                                    uint256,
                                    bytes calldata
                                ) external virtual returns (bytes4) {
                                    return ERC721TokenReceiver.onERC721Received.selector;
                                }
                            }
                            // SPDX-License-Identifier: AGPL-3.0-only
                            pragma solidity >=0.8.0;
                            import {ERC20} from "../tokens/ERC20.sol";
                            /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
                            /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
                            /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
                            /// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
                            library SafeTransferLib {
                                /*//////////////////////////////////////////////////////////////
                                                         ETH OPERATIONS
                                //////////////////////////////////////////////////////////////*/
                                function safeTransferETH(address to, uint256 amount) internal {
                                    bool success;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        // Transfer the ETH and store if it succeeded or not.
                                        success := call(gas(), to, amount, 0, 0, 0, 0)
                                    }
                                    require(success, "ETH_TRANSFER_FAILED");
                                }
                                /*//////////////////////////////////////////////////////////////
                                                        ERC20 OPERATIONS
                                //////////////////////////////////////////////////////////////*/
                                function safeTransferFrom(
                                    ERC20 token,
                                    address from,
                                    address to,
                                    uint256 amount
                                ) internal {
                                    bool success;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        // Get a pointer to some free memory.
                                        let freeMemoryPointer := mload(0x40)
                                        // Write the abi-encoded calldata into memory, beginning with the function selector.
                                        mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
                                        mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
                                        mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
                                        mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.
                                        success := and(
                                            // Set success to whether the call reverted, if not we check it either
                                            // returned exactly 1 (can't just be non-zero data), or had no return data.
                                            or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                                            // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                                            // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                                            // Counterintuitively, this call must be positioned second to the or() call in the
                                            // surrounding and() call or else returndatasize() will be zero during the computation.
                                            call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
                                        )
                                    }
                                    require(success, "TRANSFER_FROM_FAILED");
                                }
                                function safeTransfer(
                                    ERC20 token,
                                    address to,
                                    uint256 amount
                                ) internal {
                                    bool success;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        // Get a pointer to some free memory.
                                        let freeMemoryPointer := mload(0x40)
                                        // Write the abi-encoded calldata into memory, beginning with the function selector.
                                        mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                                        mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
                                        mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
                                        success := and(
                                            // Set success to whether the call reverted, if not we check it either
                                            // returned exactly 1 (can't just be non-zero data), or had no return data.
                                            or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                                            // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                                            // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                                            // Counterintuitively, this call must be positioned second to the or() call in the
                                            // surrounding and() call or else returndatasize() will be zero during the computation.
                                            call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
                                        )
                                    }
                                    require(success, "TRANSFER_FAILED");
                                }
                                function safeApprove(
                                    ERC20 token,
                                    address to,
                                    uint256 amount
                                ) internal {
                                    bool success;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        // Get a pointer to some free memory.
                                        let freeMemoryPointer := mload(0x40)
                                        // Write the abi-encoded calldata into memory, beginning with the function selector.
                                        mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
                                        mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
                                        mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
                                        success := and(
                                            // Set success to whether the call reverted, if not we check it either
                                            // returned exactly 1 (can't just be non-zero data), or had no return data.
                                            or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                                            // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                                            // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                                            // Counterintuitively, this call must be positioned second to the or() call in the
                                            // surrounding and() call or else returndatasize() will be zero during the computation.
                                            call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
                                        )
                                    }
                                    require(success, "APPROVE_FAILED");
                                }
                            }
                            pragma solidity >=0.5.0;
                            interface IUniswapV2Pair {
                                event Approval(address indexed owner, address indexed spender, uint value);
                                event Transfer(address indexed from, address indexed to, uint value);
                                function name() external pure returns (string memory);
                                function symbol() external pure returns (string memory);
                                function decimals() external pure returns (uint8);
                                function totalSupply() external view returns (uint);
                                function balanceOf(address owner) external view returns (uint);
                                function allowance(address owner, address spender) external view returns (uint);
                                function approve(address spender, uint value) external returns (bool);
                                function transfer(address to, uint value) external returns (bool);
                                function transferFrom(address from, address to, uint value) external returns (bool);
                                function DOMAIN_SEPARATOR() external view returns (bytes32);
                                function PERMIT_TYPEHASH() external pure returns (bytes32);
                                function nonces(address owner) external view returns (uint);
                                function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
                                event Mint(address indexed sender, uint amount0, uint amount1);
                                event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                                event Swap(
                                    address indexed sender,
                                    uint amount0In,
                                    uint amount1In,
                                    uint amount0Out,
                                    uint amount1Out,
                                    address indexed to
                                );
                                event Sync(uint112 reserve0, uint112 reserve1);
                                function MINIMUM_LIQUIDITY() external pure returns (uint);
                                function factory() external view returns (address);
                                function token0() external view returns (address);
                                function token1() external view returns (address);
                                function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
                                function price0CumulativeLast() external view returns (uint);
                                function price1CumulativeLast() external view returns (uint);
                                function kLast() external view returns (uint);
                                function mint(address to) external returns (uint liquidity);
                                function burn(address to) external returns (uint amount0, uint amount1);
                                function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
                                function skim(address to) external;
                                function sync() external;
                                function initialize(address, address) external;
                            }
                            // SPDX-License-Identifier: GPL-2.0-or-later
                            pragma solidity >=0.5.0;
                            import './pool/IUniswapV3PoolImmutables.sol';
                            import './pool/IUniswapV3PoolState.sol';
                            import './pool/IUniswapV3PoolDerivedState.sol';
                            import './pool/IUniswapV3PoolActions.sol';
                            import './pool/IUniswapV3PoolOwnerActions.sol';
                            import './pool/IUniswapV3PoolEvents.sol';
                            /// @title The interface for a Uniswap V3 Pool
                            /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
                            /// to the ERC20 specification
                            /// @dev The pool interface is broken up into many smaller pieces
                            interface IUniswapV3Pool is
                                IUniswapV3PoolImmutables,
                                IUniswapV3PoolState,
                                IUniswapV3PoolDerivedState,
                                IUniswapV3PoolActions,
                                IUniswapV3PoolOwnerActions,
                                IUniswapV3PoolEvents
                            {
                            }
                            // SPDX-License-Identifier: GPL-2.0-or-later
                            pragma solidity >=0.5.0;
                            /// @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;
                            }
                            // SPDX-License-Identifier: GPL-2.0-or-later
                            pragma solidity >=0.5.0;
                            /// @title Permissionless pool actions
                            /// @notice Contains pool methods that can be called by anyone
                            interface IUniswapV3PoolActions {
                                /// @notice Sets the initial price for the pool
                                /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
                                /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
                                function initialize(uint160 sqrtPriceX96) external;
                                /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
                                /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
                                /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
                                /// on tickLower, tickUpper, the amount of liquidity, and the current price.
                                /// @param recipient The address for which the liquidity will be created
                                /// @param tickLower The lower tick of the position in which to add liquidity
                                /// @param tickUpper The upper tick of the position in which to add liquidity
                                /// @param amount The amount of liquidity to mint
                                /// @param data Any data that should be passed through to the callback
                                /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
                                /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
                                function mint(
                                    address recipient,
                                    int24 tickLower,
                                    int24 tickUpper,
                                    uint128 amount,
                                    bytes calldata data
                                ) external returns (uint256 amount0, uint256 amount1);
                                /// @notice Collects tokens owed to a position
                                /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
                                /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
                                /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
                                /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
                                /// @param recipient The address which should receive the fees collected
                                /// @param tickLower The lower tick of the position for which to collect fees
                                /// @param tickUpper The upper tick of the position for which to collect fees
                                /// @param amount0Requested How much token0 should be withdrawn from the fees owed
                                /// @param amount1Requested How much token1 should be withdrawn from the fees owed
                                /// @return amount0 The amount of fees collected in token0
                                /// @return amount1 The amount of fees collected in token1
                                function collect(
                                    address recipient,
                                    int24 tickLower,
                                    int24 tickUpper,
                                    uint128 amount0Requested,
                                    uint128 amount1Requested
                                ) external returns (uint128 amount0, uint128 amount1);
                                /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
                                /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
                                /// @dev Fees must be collected separately via a call to #collect
                                /// @param tickLower The lower tick of the position for which to burn liquidity
                                /// @param tickUpper The upper tick of the position for which to burn liquidity
                                /// @param amount How much liquidity to burn
                                /// @return amount0 The amount of token0 sent to the recipient
                                /// @return amount1 The amount of token1 sent to the recipient
                                function burn(
                                    int24 tickLower,
                                    int24 tickUpper,
                                    uint128 amount
                                ) external returns (uint256 amount0, uint256 amount1);
                                /// @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 Receive token0 and/or token1 and pay it back, plus a fee, in the callback
                                /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
                                /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
                                /// with 0 amount{0,1} and sending the donation amount(s) from the callback
                                /// @param recipient The address which will receive the token0 and token1 amounts
                                /// @param amount0 The amount of token0 to send
                                /// @param amount1 The amount of token1 to send
                                /// @param data Any data to be passed through to the callback
                                function flash(
                                    address recipient,
                                    uint256 amount0,
                                    uint256 amount1,
                                    bytes calldata data
                                ) external;
                                /// @notice Increase the maximum number of price and liquidity observations that this pool will store
                                /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
                                /// the input observationCardinalityNext.
                                /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
                                function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
                            }
                            // SPDX-License-Identifier: GPL-2.0-or-later
                            pragma solidity >=0.5.0;
                            /// @title Pool state that is not stored
                            /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
                            /// blockchain. The functions here may have variable gas costs.
                            interface IUniswapV3PoolDerivedState {
                                /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
                                /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
                                /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
                                /// you must call it with secondsAgos = [3600, 0].
                                /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
                                /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
                                /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
                                /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
                                /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
                                /// timestamp
                                function observe(uint32[] calldata secondsAgos)
                                    external
                                    view
                                    returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
                                /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
                                /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
                                /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
                                /// snapshot is taken and the second snapshot is taken.
                                /// @param tickLower The lower tick of the range
                                /// @param tickUpper The upper tick of the range
                                /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
                                /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
                                /// @return secondsInside The snapshot of seconds per liquidity for the range
                                function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
                                    external
                                    view
                                    returns (
                                        int56 tickCumulativeInside,
                                        uint160 secondsPerLiquidityInsideX128,
                                        uint32 secondsInside
                                    );
                            }
                            // SPDX-License-Identifier: GPL-2.0-or-later
                            pragma solidity >=0.5.0;
                            /// @title Events emitted by a pool
                            /// @notice Contains all events emitted by the pool
                            interface IUniswapV3PoolEvents {
                                /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
                                /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
                                /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
                                /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
                                event Initialize(uint160 sqrtPriceX96, int24 tick);
                                /// @notice Emitted when liquidity is minted for a given position
                                /// @param sender The address that minted the liquidity
                                /// @param owner The owner of the position and recipient of any minted liquidity
                                /// @param tickLower The lower tick of the position
                                /// @param tickUpper The upper tick of the position
                                /// @param amount The amount of liquidity minted to the position range
                                /// @param amount0 How much token0 was required for the minted liquidity
                                /// @param amount1 How much token1 was required for the minted liquidity
                                event Mint(
                                    address sender,
                                    address indexed owner,
                                    int24 indexed tickLower,
                                    int24 indexed tickUpper,
                                    uint128 amount,
                                    uint256 amount0,
                                    uint256 amount1
                                );
                                /// @notice Emitted when fees are collected by the owner of a position
                                /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
                                /// @param owner The owner of the position for which fees are collected
                                /// @param tickLower The lower tick of the position
                                /// @param tickUpper The upper tick of the position
                                /// @param amount0 The amount of token0 fees collected
                                /// @param amount1 The amount of token1 fees collected
                                event Collect(
                                    address indexed owner,
                                    address recipient,
                                    int24 indexed tickLower,
                                    int24 indexed tickUpper,
                                    uint128 amount0,
                                    uint128 amount1
                                );
                                /// @notice Emitted when a position's liquidity is removed
                                /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
                                /// @param owner The owner of the position for which liquidity is removed
                                /// @param tickLower The lower tick of the position
                                /// @param tickUpper The upper tick of the position
                                /// @param amount The amount of liquidity to remove
                                /// @param amount0 The amount of token0 withdrawn
                                /// @param amount1 The amount of token1 withdrawn
                                event Burn(
                                    address indexed owner,
                                    int24 indexed tickLower,
                                    int24 indexed tickUpper,
                                    uint128 amount,
                                    uint256 amount0,
                                    uint256 amount1
                                );
                                /// @notice Emitted by the pool for any swaps between token0 and token1
                                /// @param sender The address that initiated the swap call, and that received the callback
                                /// @param recipient The address that received the output of the swap
                                /// @param amount0 The delta of the token0 balance of the pool
                                /// @param amount1 The delta of the token1 balance of the pool
                                /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
                                /// @param liquidity The liquidity of the pool after the swap
                                /// @param tick The log base 1.0001 of price of the pool after the swap
                                event Swap(
                                    address indexed sender,
                                    address indexed recipient,
                                    int256 amount0,
                                    int256 amount1,
                                    uint160 sqrtPriceX96,
                                    uint128 liquidity,
                                    int24 tick
                                );
                                /// @notice Emitted by the pool for any flashes of token0/token1
                                /// @param sender The address that initiated the swap call, and that received the callback
                                /// @param recipient The address that received the tokens from flash
                                /// @param amount0 The amount of token0 that was flashed
                                /// @param amount1 The amount of token1 that was flashed
                                /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
                                /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
                                event Flash(
                                    address indexed sender,
                                    address indexed recipient,
                                    uint256 amount0,
                                    uint256 amount1,
                                    uint256 paid0,
                                    uint256 paid1
                                );
                                /// @notice Emitted by the pool for increases to the number of observations that can be stored
                                /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
                                /// just before a mint/swap/burn.
                                /// @param observationCardinalityNextOld The previous value of the next observation cardinality
                                /// @param observationCardinalityNextNew The updated value of the next observation cardinality
                                event IncreaseObservationCardinalityNext(
                                    uint16 observationCardinalityNextOld,
                                    uint16 observationCardinalityNextNew
                                );
                                /// @notice Emitted when the protocol fee is changed by the pool
                                /// @param feeProtocol0Old The previous value of the token0 protocol fee
                                /// @param feeProtocol1Old The previous value of the token1 protocol fee
                                /// @param feeProtocol0New The updated value of the token0 protocol fee
                                /// @param feeProtocol1New The updated value of the token1 protocol fee
                                event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
                                /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
                                /// @param sender The address that collects the protocol fees
                                /// @param recipient The address that receives the collected protocol fees
                                /// @param amount0 The amount of token0 protocol fees that is withdrawn
                                /// @param amount0 The amount of token1 protocol fees that is withdrawn
                                event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
                            }
                            // SPDX-License-Identifier: GPL-2.0-or-later
                            pragma solidity >=0.5.0;
                            /// @title Pool state that never changes
                            /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
                            interface IUniswapV3PoolImmutables {
                                /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
                                /// @return The contract address
                                function factory() external view returns (address);
                                /// @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);
                                /// @notice The pool tick spacing
                                /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
                                /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
                                /// This value is an int24 to avoid casting even though it is always positive.
                                /// @return The tick spacing
                                function tickSpacing() external view returns (int24);
                                /// @notice The maximum amount of position liquidity that can use any tick in the range
                                /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
                                /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
                                /// @return The max amount of liquidity per tick
                                function maxLiquidityPerTick() external view returns (uint128);
                            }
                            // SPDX-License-Identifier: GPL-2.0-or-later
                            pragma solidity >=0.5.0;
                            /// @title Permissioned pool actions
                            /// @notice Contains pool methods that may only be called by the factory owner
                            interface IUniswapV3PoolOwnerActions {
                                /// @notice Set the denominator of the protocol's % share of the fees
                                /// @param feeProtocol0 new protocol fee for token0 of the pool
                                /// @param feeProtocol1 new protocol fee for token1 of the pool
                                function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
                                /// @notice Collect the protocol fee accrued to the pool
                                /// @param recipient The address to which collected protocol fees should be sent
                                /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
                                /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
                                /// @return amount0 The protocol fee collected in token0
                                /// @return amount1 The protocol fee collected in token1
                                function collectProtocol(
                                    address recipient,
                                    uint128 amount0Requested,
                                    uint128 amount1Requested
                                ) external returns (uint128 amount0, uint128 amount1);
                            }
                            // SPDX-License-Identifier: GPL-2.0-or-later
                            pragma solidity >=0.5.0;
                            /// @title Pool state that can change
                            /// @notice These methods compose the pool's state, and can change with any frequency including multiple times
                            /// per transaction
                            interface IUniswapV3PoolState {
                                /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
                                /// when accessed externally.
                                /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
                                /// tick The current tick of the pool, i.e. according to the last tick transition that was run.
                                /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
                                /// boundary.
                                /// observationIndex The index of the last oracle observation that was written,
                                /// observationCardinality The current maximum number of observations stored in the pool,
                                /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
                                /// feeProtocol The protocol fee for both tokens of the pool.
                                /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
                                /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
                                /// unlocked Whether the pool is currently locked to reentrancy
                                function slot0()
                                    external
                                    view
                                    returns (
                                        uint160 sqrtPriceX96,
                                        int24 tick,
                                        uint16 observationIndex,
                                        uint16 observationCardinality,
                                        uint16 observationCardinalityNext,
                                        uint8 feeProtocol,
                                        bool unlocked
                                    );
                                /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
                                /// @dev This value can overflow the uint256
                                function feeGrowthGlobal0X128() external view returns (uint256);
                                /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
                                /// @dev This value can overflow the uint256
                                function feeGrowthGlobal1X128() external view returns (uint256);
                                /// @notice The amounts of token0 and token1 that are owed to the protocol
                                /// @dev Protocol fees will never exceed uint128 max in either token
                                function protocolFees() external view returns (uint128 token0, uint128 token1);
                                /// @notice The currently in range liquidity available to the pool
                                /// @dev This value has no relationship to the total liquidity across all ticks
                                function liquidity() external view returns (uint128);
                                /// @notice Look up information about a specific tick in the pool
                                /// @param tick The tick to look up
                                /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
                                /// tick upper,
                                /// liquidityNet how much liquidity changes when the pool price crosses the tick,
                                /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
                                /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
                                /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
                                /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
                                /// secondsOutside the seconds spent on the other side of the tick from the current tick,
                                /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
                                /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
                                /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
                                /// a specific position.
                                function ticks(int24 tick)
                                    external
                                    view
                                    returns (
                                        uint128 liquidityGross,
                                        int128 liquidityNet,
                                        uint256 feeGrowthOutside0X128,
                                        uint256 feeGrowthOutside1X128,
                                        int56 tickCumulativeOutside,
                                        uint160 secondsPerLiquidityOutsideX128,
                                        uint32 secondsOutside,
                                        bool initialized
                                    );
                                /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
                                function tickBitmap(int16 wordPosition) external view returns (uint256);
                                /// @notice Returns the information about a position by the position's key
                                /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
                                /// @return _liquidity The amount of liquidity in the position,
                                /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
                                /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
                                /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
                                /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
                                function positions(bytes32 key)
                                    external
                                    view
                                    returns (
                                        uint128 _liquidity,
                                        uint256 feeGrowthInside0LastX128,
                                        uint256 feeGrowthInside1LastX128,
                                        uint128 tokensOwed0,
                                        uint128 tokensOwed1
                                    );
                                /// @notice Returns data about a specific observation index
                                /// @param index The element of the observations array to fetch
                                /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
                                /// ago, rather than at a specific index in the array.
                                /// @return blockTimestamp The timestamp of the observation,
                                /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
                                /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
                                /// Returns initialized whether the observation has been initialized and the values are safe to use
                                function observations(uint256 index)
                                    external
                                    view
                                    returns (
                                        uint32 blockTimestamp,
                                        int56 tickCumulative,
                                        uint160 secondsPerLiquidityCumulativeX128,
                                        bool initialized
                                    );
                            }
                            // SPDX-License-Identifier: GPL-2.0-or-later
                            pragma solidity >=0.5.0;
                            /// @title Safe casting methods
                            /// @notice Contains methods for safely casting between types
                            library SafeCast {
                                /// @notice Cast a uint256 to a uint160, revert on overflow
                                /// @param y The uint256 to be downcasted
                                /// @return z The downcasted integer, now type uint160
                                function toUint160(uint256 y) internal pure returns (uint160 z) {
                                    require((z = uint160(y)) == y);
                                }
                                /// @notice Cast a int256 to a int128, revert on overflow or underflow
                                /// @param y The int256 to be downcasted
                                /// @return z The downcasted integer, now type int128
                                function toInt128(int256 y) internal pure returns (int128 z) {
                                    require((z = int128(y)) == y);
                                }
                                /// @notice Cast a uint256 to a int256, revert on overflow
                                /// @param y The uint256 to be casted
                                /// @return z The casted integer, now type int256
                                function toInt256(uint256 y) internal pure returns (int256 z) {
                                    require(y < 2**255);
                                    z = int256(y);
                                }
                            }
                            

                            File 2 of 10: Permit2
                            // SPDX-License-Identifier: AGPL-3.0-only
                            pragma solidity >=0.8.0;
                            /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
                            /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
                            /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
                            /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
                            abstract contract ERC20 {
                                /*//////////////////////////////////////////////////////////////
                                                             EVENTS
                                //////////////////////////////////////////////////////////////*/
                                event Transfer(address indexed from, address indexed to, uint256 amount);
                                event Approval(address indexed owner, address indexed spender, uint256 amount);
                                /*//////////////////////////////////////////////////////////////
                                                        METADATA STORAGE
                                //////////////////////////////////////////////////////////////*/
                                string public name;
                                string public symbol;
                                uint8 public immutable decimals;
                                /*//////////////////////////////////////////////////////////////
                                                          ERC20 STORAGE
                                //////////////////////////////////////////////////////////////*/
                                uint256 public totalSupply;
                                mapping(address => uint256) public balanceOf;
                                mapping(address => mapping(address => uint256)) public allowance;
                                /*//////////////////////////////////////////////////////////////
                                                        EIP-2612 STORAGE
                                //////////////////////////////////////////////////////////////*/
                                uint256 internal immutable INITIAL_CHAIN_ID;
                                bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
                                mapping(address => uint256) public nonces;
                                /*//////////////////////////////////////////////////////////////
                                                           CONSTRUCTOR
                                //////////////////////////////////////////////////////////////*/
                                constructor(
                                    string memory _name,
                                    string memory _symbol,
                                    uint8 _decimals
                                ) {
                                    name = _name;
                                    symbol = _symbol;
                                    decimals = _decimals;
                                    INITIAL_CHAIN_ID = block.chainid;
                                    INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
                                }
                                /*//////////////////////////////////////////////////////////////
                                                           ERC20 LOGIC
                                //////////////////////////////////////////////////////////////*/
                                function approve(address spender, uint256 amount) public virtual returns (bool) {
                                    allowance[msg.sender][spender] = amount;
                                    emit Approval(msg.sender, spender, amount);
                                    return true;
                                }
                                function transfer(address to, uint256 amount) public virtual returns (bool) {
                                    balanceOf[msg.sender] -= amount;
                                    // Cannot overflow because the sum of all user
                                    // balances can't exceed the max uint256 value.
                                    unchecked {
                                        balanceOf[to] += amount;
                                    }
                                    emit Transfer(msg.sender, to, amount);
                                    return true;
                                }
                                function transferFrom(
                                    address from,
                                    address to,
                                    uint256 amount
                                ) public virtual returns (bool) {
                                    uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
                                    if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
                                    balanceOf[from] -= amount;
                                    // Cannot overflow because the sum of all user
                                    // balances can't exceed the max uint256 value.
                                    unchecked {
                                        balanceOf[to] += amount;
                                    }
                                    emit Transfer(from, to, amount);
                                    return true;
                                }
                                /*//////////////////////////////////////////////////////////////
                                                         EIP-2612 LOGIC
                                //////////////////////////////////////////////////////////////*/
                                function permit(
                                    address owner,
                                    address spender,
                                    uint256 value,
                                    uint256 deadline,
                                    uint8 v,
                                    bytes32 r,
                                    bytes32 s
                                ) public virtual {
                                    require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
                                    // Unchecked because the only math done is incrementing
                                    // the owner's nonce which cannot realistically overflow.
                                    unchecked {
                                        address recoveredAddress = ecrecover(
                                            keccak256(
                                                abi.encodePacked(
                                                    "\\x19\\x01",
                                                    DOMAIN_SEPARATOR(),
                                                    keccak256(
                                                        abi.encode(
                                                            keccak256(
                                                                "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                                            ),
                                                            owner,
                                                            spender,
                                                            value,
                                                            nonces[owner]++,
                                                            deadline
                                                        )
                                                    )
                                                )
                                            ),
                                            v,
                                            r,
                                            s
                                        );
                                        require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
                                        allowance[recoveredAddress][spender] = value;
                                    }
                                    emit Approval(owner, spender, value);
                                }
                                function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
                                    return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
                                }
                                function computeDomainSeparator() internal view virtual returns (bytes32) {
                                    return
                                        keccak256(
                                            abi.encode(
                                                keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                                keccak256(bytes(name)),
                                                keccak256("1"),
                                                block.chainid,
                                                address(this)
                                            )
                                        );
                                }
                                /*//////////////////////////////////////////////////////////////
                                                    INTERNAL MINT/BURN LOGIC
                                //////////////////////////////////////////////////////////////*/
                                function _mint(address to, uint256 amount) internal virtual {
                                    totalSupply += amount;
                                    // Cannot overflow because the sum of all user
                                    // balances can't exceed the max uint256 value.
                                    unchecked {
                                        balanceOf[to] += amount;
                                    }
                                    emit Transfer(address(0), to, amount);
                                }
                                function _burn(address from, uint256 amount) internal virtual {
                                    balanceOf[from] -= amount;
                                    // Cannot underflow because a user's balance
                                    // will never be larger than the total supply.
                                    unchecked {
                                        totalSupply -= amount;
                                    }
                                    emit Transfer(from, address(0), amount);
                                }
                            }
                            // SPDX-License-Identifier: AGPL-3.0-only
                            pragma solidity >=0.8.0;
                            import {ERC20} from "../tokens/ERC20.sol";
                            /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
                            /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
                            /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
                            /// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
                            library SafeTransferLib {
                                /*//////////////////////////////////////////////////////////////
                                                         ETH OPERATIONS
                                //////////////////////////////////////////////////////////////*/
                                function safeTransferETH(address to, uint256 amount) internal {
                                    bool success;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        // Transfer the ETH and store if it succeeded or not.
                                        success := call(gas(), to, amount, 0, 0, 0, 0)
                                    }
                                    require(success, "ETH_TRANSFER_FAILED");
                                }
                                /*//////////////////////////////////////////////////////////////
                                                        ERC20 OPERATIONS
                                //////////////////////////////////////////////////////////////*/
                                function safeTransferFrom(
                                    ERC20 token,
                                    address from,
                                    address to,
                                    uint256 amount
                                ) internal {
                                    bool success;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        // Get a pointer to some free memory.
                                        let freeMemoryPointer := mload(0x40)
                                        // Write the abi-encoded calldata into memory, beginning with the function selector.
                                        mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
                                        mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
                                        mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
                                        mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.
                                        success := and(
                                            // Set success to whether the call reverted, if not we check it either
                                            // returned exactly 1 (can't just be non-zero data), or had no return data.
                                            or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                                            // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                                            // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                                            // Counterintuitively, this call must be positioned second to the or() call in the
                                            // surrounding and() call or else returndatasize() will be zero during the computation.
                                            call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
                                        )
                                    }
                                    require(success, "TRANSFER_FROM_FAILED");
                                }
                                function safeTransfer(
                                    ERC20 token,
                                    address to,
                                    uint256 amount
                                ) internal {
                                    bool success;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        // Get a pointer to some free memory.
                                        let freeMemoryPointer := mload(0x40)
                                        // Write the abi-encoded calldata into memory, beginning with the function selector.
                                        mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                                        mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
                                        mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
                                        success := and(
                                            // Set success to whether the call reverted, if not we check it either
                                            // returned exactly 1 (can't just be non-zero data), or had no return data.
                                            or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                                            // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                                            // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                                            // Counterintuitively, this call must be positioned second to the or() call in the
                                            // surrounding and() call or else returndatasize() will be zero during the computation.
                                            call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
                                        )
                                    }
                                    require(success, "TRANSFER_FAILED");
                                }
                                function safeApprove(
                                    ERC20 token,
                                    address to,
                                    uint256 amount
                                ) internal {
                                    bool success;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        // Get a pointer to some free memory.
                                        let freeMemoryPointer := mload(0x40)
                                        // Write the abi-encoded calldata into memory, beginning with the function selector.
                                        mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
                                        mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
                                        mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
                                        success := and(
                                            // Set success to whether the call reverted, if not we check it either
                                            // returned exactly 1 (can't just be non-zero data), or had no return data.
                                            or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                                            // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                                            // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                                            // Counterintuitively, this call must be positioned second to the or() call in the
                                            // surrounding and() call or else returndatasize() will be zero during the computation.
                                            call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
                                        )
                                    }
                                    require(success, "APPROVE_FAILED");
                                }
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity 0.8.17;
                            import {ERC20} from "solmate/tokens/ERC20.sol";
                            import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol";
                            import {PermitHash} from "./libraries/PermitHash.sol";
                            import {SignatureVerification} from "./libraries/SignatureVerification.sol";
                            import {EIP712} from "./EIP712.sol";
                            import {IAllowanceTransfer} from "../src/interfaces/IAllowanceTransfer.sol";
                            import {SignatureExpired, InvalidNonce} from "./PermitErrors.sol";
                            import {Allowance} from "./libraries/Allowance.sol";
                            contract AllowanceTransfer is IAllowanceTransfer, EIP712 {
                                using SignatureVerification for bytes;
                                using SafeTransferLib for ERC20;
                                using PermitHash for PermitSingle;
                                using PermitHash for PermitBatch;
                                using Allowance for PackedAllowance;
                                /// @notice Maps users to tokens to spender addresses and information about the approval on the token
                                /// @dev Indexed in the order of token owner address, token address, spender address
                                /// @dev The stored word saves the allowed amount, expiration on the allowance, and nonce
                                mapping(address => mapping(address => mapping(address => PackedAllowance))) public allowance;
                                /// @inheritdoc IAllowanceTransfer
                                function approve(address token, address spender, uint160 amount, uint48 expiration) external {
                                    PackedAllowance storage allowed = allowance[msg.sender][token][spender];
                                    allowed.updateAmountAndExpiration(amount, expiration);
                                    emit Approval(msg.sender, token, spender, amount, expiration);
                                }
                                /// @inheritdoc IAllowanceTransfer
                                function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external {
                                    if (block.timestamp > permitSingle.sigDeadline) revert SignatureExpired(permitSingle.sigDeadline);
                                    // Verify the signer address from the signature.
                                    signature.verify(_hashTypedData(permitSingle.hash()), owner);
                                    _updateApproval(permitSingle.details, owner, permitSingle.spender);
                                }
                                /// @inheritdoc IAllowanceTransfer
                                function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external {
                                    if (block.timestamp > permitBatch.sigDeadline) revert SignatureExpired(permitBatch.sigDeadline);
                                    // Verify the signer address from the signature.
                                    signature.verify(_hashTypedData(permitBatch.hash()), owner);
                                    address spender = permitBatch.spender;
                                    unchecked {
                                        uint256 length = permitBatch.details.length;
                                        for (uint256 i = 0; i < length; ++i) {
                                            _updateApproval(permitBatch.details[i], owner, spender);
                                        }
                                    }
                                }
                                /// @inheritdoc IAllowanceTransfer
                                function transferFrom(address from, address to, uint160 amount, address token) external {
                                    _transfer(from, to, amount, token);
                                }
                                /// @inheritdoc IAllowanceTransfer
                                function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external {
                                    unchecked {
                                        uint256 length = transferDetails.length;
                                        for (uint256 i = 0; i < length; ++i) {
                                            AllowanceTransferDetails memory transferDetail = transferDetails[i];
                                            _transfer(transferDetail.from, transferDetail.to, transferDetail.amount, transferDetail.token);
                                        }
                                    }
                                }
                                /// @notice Internal function for transferring tokens using stored allowances
                                /// @dev Will fail if the allowed timeframe has passed
                                function _transfer(address from, address to, uint160 amount, address token) private {
                                    PackedAllowance storage allowed = allowance[from][token][msg.sender];
                                    if (block.timestamp > allowed.expiration) revert AllowanceExpired(allowed.expiration);
                                    uint256 maxAmount = allowed.amount;
                                    if (maxAmount != type(uint160).max) {
                                        if (amount > maxAmount) {
                                            revert InsufficientAllowance(maxAmount);
                                        } else {
                                            unchecked {
                                                allowed.amount = uint160(maxAmount) - amount;
                                            }
                                        }
                                    }
                                    // Transfer the tokens from the from address to the recipient.
                                    ERC20(token).safeTransferFrom(from, to, amount);
                                }
                                /// @inheritdoc IAllowanceTransfer
                                function lockdown(TokenSpenderPair[] calldata approvals) external {
                                    address owner = msg.sender;
                                    // Revoke allowances for each pair of spenders and tokens.
                                    unchecked {
                                        uint256 length = approvals.length;
                                        for (uint256 i = 0; i < length; ++i) {
                                            address token = approvals[i].token;
                                            address spender = approvals[i].spender;
                                            allowance[owner][token][spender].amount = 0;
                                            emit Lockdown(owner, token, spender);
                                        }
                                    }
                                }
                                /// @inheritdoc IAllowanceTransfer
                                function invalidateNonces(address token, address spender, uint48 newNonce) external {
                                    uint48 oldNonce = allowance[msg.sender][token][spender].nonce;
                                    if (newNonce <= oldNonce) revert InvalidNonce();
                                    // Limit the amount of nonces that can be invalidated in one transaction.
                                    unchecked {
                                        uint48 delta = newNonce - oldNonce;
                                        if (delta > type(uint16).max) revert ExcessiveInvalidation();
                                    }
                                    allowance[msg.sender][token][spender].nonce = newNonce;
                                    emit NonceInvalidation(msg.sender, token, spender, newNonce, oldNonce);
                                }
                                /// @notice Sets the new values for amount, expiration, and nonce.
                                /// @dev Will check that the signed nonce is equal to the current nonce and then incrememnt the nonce value by 1.
                                /// @dev Emits a Permit event.
                                function _updateApproval(PermitDetails memory details, address owner, address spender) private {
                                    uint48 nonce = details.nonce;
                                    address token = details.token;
                                    uint160 amount = details.amount;
                                    uint48 expiration = details.expiration;
                                    PackedAllowance storage allowed = allowance[owner][token][spender];
                                    if (allowed.nonce != nonce) revert InvalidNonce();
                                    allowed.updateAll(amount, expiration, nonce);
                                    emit Permit(owner, token, spender, amount, expiration, nonce);
                                }
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity 0.8.17;
                            /// @notice EIP712 helpers for permit2
                            /// @dev Maintains cross-chain replay protection in the event of a fork
                            /// @dev Reference: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/EIP712.sol
                            contract EIP712 {
                                // 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;
                                bytes32 private constant _HASHED_NAME = keccak256("Permit2");
                                bytes32 private constant _TYPE_HASH =
                                    keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
                                constructor() {
                                    _CACHED_CHAIN_ID = block.chainid;
                                    _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME);
                                }
                                /// @notice Returns the domain separator for the current chain.
                                /// @dev Uses cached version if chainid and address are unchanged from construction.
                                function DOMAIN_SEPARATOR() public view returns (bytes32) {
                                    return block.chainid == _CACHED_CHAIN_ID
                                        ? _CACHED_DOMAIN_SEPARATOR
                                        : _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME);
                                }
                                /// @notice Builds a domain separator using the current chainId and contract address.
                                function _buildDomainSeparator(bytes32 typeHash, bytes32 nameHash) private view returns (bytes32) {
                                    return keccak256(abi.encode(typeHash, nameHash, block.chainid, address(this)));
                                }
                                /// @notice Creates an EIP-712 typed data hash
                                function _hashTypedData(bytes32 dataHash) internal view returns (bytes32) {
                                    return keccak256(abi.encodePacked("\\x19\\x01", DOMAIN_SEPARATOR(), dataHash));
                                }
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity 0.8.17;
                            import {SignatureTransfer} from "./SignatureTransfer.sol";
                            import {AllowanceTransfer} from "./AllowanceTransfer.sol";
                            /// @notice Permit2 handles signature-based transfers in SignatureTransfer and allowance-based transfers in AllowanceTransfer.
                            /// @dev Users must approve Permit2 before calling any of the transfer functions.
                            contract Permit2 is SignatureTransfer, AllowanceTransfer {
                            // Permit2 unifies the two contracts so users have maximal flexibility with their approval.
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity 0.8.17;
                            /// @notice Shared errors between signature based transfers and allowance based transfers.
                            /// @notice Thrown when validating an inputted signature that is stale
                            /// @param signatureDeadline The timestamp at which a signature is no longer valid
                            error SignatureExpired(uint256 signatureDeadline);
                            /// @notice Thrown when validating that the inputted nonce has not been used
                            error InvalidNonce();
                            // SPDX-License-Identifier: MIT
                            pragma solidity 0.8.17;
                            import {ISignatureTransfer} from "./interfaces/ISignatureTransfer.sol";
                            import {SignatureExpired, InvalidNonce} from "./PermitErrors.sol";
                            import {ERC20} from "solmate/tokens/ERC20.sol";
                            import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol";
                            import {SignatureVerification} from "./libraries/SignatureVerification.sol";
                            import {PermitHash} from "./libraries/PermitHash.sol";
                            import {EIP712} from "./EIP712.sol";
                            contract SignatureTransfer is ISignatureTransfer, EIP712 {
                                using SignatureVerification for bytes;
                                using SafeTransferLib for ERC20;
                                using PermitHash for PermitTransferFrom;
                                using PermitHash for PermitBatchTransferFrom;
                                /// @inheritdoc ISignatureTransfer
                                mapping(address => mapping(uint256 => uint256)) public nonceBitmap;
                                /// @inheritdoc ISignatureTransfer
                                function permitTransferFrom(
                                    PermitTransferFrom memory permit,
                                    SignatureTransferDetails calldata transferDetails,
                                    address owner,
                                    bytes calldata signature
                                ) external {
                                    _permitTransferFrom(permit, transferDetails, owner, permit.hash(), signature);
                                }
                                /// @inheritdoc ISignatureTransfer
                                function permitWitnessTransferFrom(
                                    PermitTransferFrom memory permit,
                                    SignatureTransferDetails calldata transferDetails,
                                    address owner,
                                    bytes32 witness,
                                    string calldata witnessTypeString,
                                    bytes calldata signature
                                ) external {
                                    _permitTransferFrom(
                                        permit, transferDetails, owner, permit.hashWithWitness(witness, witnessTypeString), signature
                                    );
                                }
                                /// @notice Transfers a token using a signed permit message.
                                /// @dev If to is the zero address, the tokens are sent to the spender.
                                /// @param permit The permit data signed over by the owner
                                /// @param dataHash The EIP-712 hash of permit data to include when checking signature
                                /// @param owner The owner of the tokens to transfer
                                /// @param transferDetails The spender's requested transfer details for the permitted token
                                /// @param signature The signature to verify
                                function _permitTransferFrom(
                                    PermitTransferFrom memory permit,
                                    SignatureTransferDetails calldata transferDetails,
                                    address owner,
                                    bytes32 dataHash,
                                    bytes calldata signature
                                ) private {
                                    uint256 requestedAmount = transferDetails.requestedAmount;
                                    if (block.timestamp > permit.deadline) revert SignatureExpired(permit.deadline);
                                    if (requestedAmount > permit.permitted.amount) revert InvalidAmount(permit.permitted.amount);
                                    _useUnorderedNonce(owner, permit.nonce);
                                    signature.verify(_hashTypedData(dataHash), owner);
                                    ERC20(permit.permitted.token).safeTransferFrom(owner, transferDetails.to, requestedAmount);
                                }
                                /// @inheritdoc ISignatureTransfer
                                function permitTransferFrom(
                                    PermitBatchTransferFrom memory permit,
                                    SignatureTransferDetails[] calldata transferDetails,
                                    address owner,
                                    bytes calldata signature
                                ) external {
                                    _permitTransferFrom(permit, transferDetails, owner, permit.hash(), signature);
                                }
                                /// @inheritdoc ISignatureTransfer
                                function permitWitnessTransferFrom(
                                    PermitBatchTransferFrom memory permit,
                                    SignatureTransferDetails[] calldata transferDetails,
                                    address owner,
                                    bytes32 witness,
                                    string calldata witnessTypeString,
                                    bytes calldata signature
                                ) external {
                                    _permitTransferFrom(
                                        permit, transferDetails, owner, permit.hashWithWitness(witness, witnessTypeString), signature
                                    );
                                }
                                /// @notice Transfers tokens using a signed permit messages
                                /// @dev If to is the zero address, the tokens are sent to the spender
                                /// @param permit The permit data signed over by the owner
                                /// @param dataHash The EIP-712 hash of permit data to include when checking signature
                                /// @param owner The owner of the tokens to transfer
                                /// @param signature The signature to verify
                                function _permitTransferFrom(
                                    PermitBatchTransferFrom memory permit,
                                    SignatureTransferDetails[] calldata transferDetails,
                                    address owner,
                                    bytes32 dataHash,
                                    bytes calldata signature
                                ) private {
                                    uint256 numPermitted = permit.permitted.length;
                                    if (block.timestamp > permit.deadline) revert SignatureExpired(permit.deadline);
                                    if (numPermitted != transferDetails.length) revert LengthMismatch();
                                    _useUnorderedNonce(owner, permit.nonce);
                                    signature.verify(_hashTypedData(dataHash), owner);
                                    unchecked {
                                        for (uint256 i = 0; i < numPermitted; ++i) {
                                            TokenPermissions memory permitted = permit.permitted[i];
                                            uint256 requestedAmount = transferDetails[i].requestedAmount;
                                            if (requestedAmount > permitted.amount) revert InvalidAmount(permitted.amount);
                                            if (requestedAmount != 0) {
                                                // allow spender to specify which of the permitted tokens should be transferred
                                                ERC20(permitted.token).safeTransferFrom(owner, transferDetails[i].to, requestedAmount);
                                            }
                                        }
                                    }
                                }
                                /// @inheritdoc ISignatureTransfer
                                function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external {
                                    nonceBitmap[msg.sender][wordPos] |= mask;
                                    emit UnorderedNonceInvalidation(msg.sender, wordPos, mask);
                                }
                                /// @notice Returns the index of the bitmap and the bit position within the bitmap. Used for unordered nonces
                                /// @param nonce The nonce to get the associated word and bit positions
                                /// @return wordPos The word position or index into the nonceBitmap
                                /// @return bitPos The bit position
                                /// @dev The first 248 bits of the nonce value is the index of the desired bitmap
                                /// @dev The last 8 bits of the nonce value is the position of the bit in the bitmap
                                function bitmapPositions(uint256 nonce) private pure returns (uint256 wordPos, uint256 bitPos) {
                                    wordPos = uint248(nonce >> 8);
                                    bitPos = uint8(nonce);
                                }
                                /// @notice Checks whether a nonce is taken and sets the bit at the bit position in the bitmap at the word position
                                /// @param from The address to use the nonce at
                                /// @param nonce The nonce to spend
                                function _useUnorderedNonce(address from, uint256 nonce) internal {
                                    (uint256 wordPos, uint256 bitPos) = bitmapPositions(nonce);
                                    uint256 bit = 1 << bitPos;
                                    uint256 flipped = nonceBitmap[from][wordPos] ^= bit;
                                    if (flipped & bit == 0) revert InvalidNonce();
                                }
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity ^0.8.17;
                            /// @title AllowanceTransfer
                            /// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
                            /// @dev Requires user's token approval on the Permit2 contract
                            interface IAllowanceTransfer {
                                /// @notice Thrown when an allowance on a token has expired.
                                /// @param deadline The timestamp at which the allowed amount is no longer valid
                                error AllowanceExpired(uint256 deadline);
                                /// @notice Thrown when an allowance on a token has been depleted.
                                /// @param amount The maximum amount allowed
                                error InsufficientAllowance(uint256 amount);
                                /// @notice Thrown when too many nonces are invalidated.
                                error ExcessiveInvalidation();
                                /// @notice Emits an event when the owner successfully invalidates an ordered nonce.
                                event NonceInvalidation(
                                    address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
                                );
                                /// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
                                event Approval(
                                    address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
                                );
                                /// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
                                event Permit(
                                    address indexed owner,
                                    address indexed token,
                                    address indexed spender,
                                    uint160 amount,
                                    uint48 expiration,
                                    uint48 nonce
                                );
                                /// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
                                event Lockdown(address indexed owner, address token, address spender);
                                /// @notice The permit data for a token
                                struct PermitDetails {
                                    // ERC20 token address
                                    address token;
                                    // the maximum amount allowed to spend
                                    uint160 amount;
                                    // timestamp at which a spender's token allowances become invalid
                                    uint48 expiration;
                                    // an incrementing value indexed per owner,token,and spender for each signature
                                    uint48 nonce;
                                }
                                /// @notice The permit message signed for a single token allownce
                                struct PermitSingle {
                                    // the permit data for a single token alownce
                                    PermitDetails details;
                                    // address permissioned on the allowed tokens
                                    address spender;
                                    // deadline on the permit signature
                                    uint256 sigDeadline;
                                }
                                /// @notice The permit message signed for multiple token allowances
                                struct PermitBatch {
                                    // the permit data for multiple token allowances
                                    PermitDetails[] details;
                                    // address permissioned on the allowed tokens
                                    address spender;
                                    // deadline on the permit signature
                                    uint256 sigDeadline;
                                }
                                /// @notice The saved permissions
                                /// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
                                /// @dev Setting amount to type(uint160).max sets an unlimited approval
                                struct PackedAllowance {
                                    // amount allowed
                                    uint160 amount;
                                    // permission expiry
                                    uint48 expiration;
                                    // an incrementing value indexed per owner,token,and spender for each signature
                                    uint48 nonce;
                                }
                                /// @notice A token spender pair.
                                struct TokenSpenderPair {
                                    // the token the spender is approved
                                    address token;
                                    // the spender address
                                    address spender;
                                }
                                /// @notice Details for a token transfer.
                                struct AllowanceTransferDetails {
                                    // the owner of the token
                                    address from;
                                    // the recipient of the token
                                    address to;
                                    // the amount of the token
                                    uint160 amount;
                                    // the token to be transferred
                                    address token;
                                }
                                /// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
                                /// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
                                /// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
                                function allowance(address, address, address) external view returns (uint160, uint48, uint48);
                                /// @notice Approves the spender to use up to amount of the specified token up until the expiration
                                /// @param token The token to approve
                                /// @param spender The spender address to approve
                                /// @param amount The approved amount of the token
                                /// @param expiration The timestamp at which the approval is no longer valid
                                /// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
                                /// @dev Setting amount to type(uint160).max sets an unlimited approval
                                function approve(address token, address spender, uint160 amount, uint48 expiration) external;
                                /// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
                                /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
                                /// @param owner The owner of the tokens being approved
                                /// @param permitSingle Data signed over by the owner specifying the terms of approval
                                /// @param signature The owner's signature over the permit data
                                function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;
                                /// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
                                /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
                                /// @param owner The owner of the tokens being approved
                                /// @param permitBatch Data signed over by the owner specifying the terms of approval
                                /// @param signature The owner's signature over the permit data
                                function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;
                                /// @notice Transfer approved tokens from one address to another
                                /// @param from The address to transfer from
                                /// @param to The address of the recipient
                                /// @param amount The amount of the token to transfer
                                /// @param token The token address to transfer
                                /// @dev Requires the from address to have approved at least the desired amount
                                /// of tokens to msg.sender.
                                function transferFrom(address from, address to, uint160 amount, address token) external;
                                /// @notice Transfer approved tokens in a batch
                                /// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
                                /// @dev Requires the from addresses to have approved at least the desired amount
                                /// of tokens to msg.sender.
                                function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;
                                /// @notice Enables performing a "lockdown" of the sender's Permit2 identity
                                /// by batch revoking approvals
                                /// @param approvals Array of approvals to revoke.
                                function lockdown(TokenSpenderPair[] calldata approvals) external;
                                /// @notice Invalidate nonces for a given (token, spender) pair
                                /// @param token The token to invalidate nonces for
                                /// @param spender The spender to invalidate nonces for
                                /// @param newNonce The new nonce to set. Invalidates all nonces less than it.
                                /// @dev Can't invalidate more than 2**16 nonces per transaction.
                                function invalidateNonces(address token, address spender, uint48 newNonce) external;
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity ^0.8.17;
                            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
                                /// @return magicValue The bytes4 magic value 0x1626ba7e
                                function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity ^0.8.17;
                            /// @title SignatureTransfer
                            /// @notice Handles ERC20 token transfers through signature based actions
                            /// @dev Requires user's token approval on the Permit2 contract
                            interface ISignatureTransfer {
                                /// @notice Thrown when the requested amount for a transfer is larger than the permissioned amount
                                /// @param maxAmount The maximum amount a spender can request to transfer
                                error InvalidAmount(uint256 maxAmount);
                                /// @notice Thrown when the number of tokens permissioned to a spender does not match the number of tokens being transferred
                                /// @dev If the spender does not need to transfer the number of tokens permitted, the spender can request amount 0 to be transferred
                                error LengthMismatch();
                                /// @notice Emits an event when the owner successfully invalidates an unordered nonce.
                                event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask);
                                /// @notice The token and amount details for a transfer signed in the permit transfer signature
                                struct TokenPermissions {
                                    // ERC20 token address
                                    address token;
                                    // the maximum amount that can be spent
                                    uint256 amount;
                                }
                                /// @notice The signed permit message for a single token transfer
                                struct PermitTransferFrom {
                                    TokenPermissions permitted;
                                    // a unique value for every token owner's signature to prevent signature replays
                                    uint256 nonce;
                                    // deadline on the permit signature
                                    uint256 deadline;
                                }
                                /// @notice Specifies the recipient address and amount for batched transfers.
                                /// @dev Recipients and amounts correspond to the index of the signed token permissions array.
                                /// @dev Reverts if the requested amount is greater than the permitted signed amount.
                                struct SignatureTransferDetails {
                                    // recipient address
                                    address to;
                                    // spender requested amount
                                    uint256 requestedAmount;
                                }
                                /// @notice Used to reconstruct the signed permit message for multiple token transfers
                                /// @dev Do not need to pass in spender address as it is required that it is msg.sender
                                /// @dev Note that a user still signs over a spender address
                                struct PermitBatchTransferFrom {
                                    // the tokens and corresponding amounts permitted for a transfer
                                    TokenPermissions[] permitted;
                                    // a unique value for every token owner's signature to prevent signature replays
                                    uint256 nonce;
                                    // deadline on the permit signature
                                    uint256 deadline;
                                }
                                /// @notice A map from token owner address and a caller specified word index to a bitmap. Used to set bits in the bitmap to prevent against signature replay protection
                                /// @dev Uses unordered nonces so that permit messages do not need to be spent in a certain order
                                /// @dev The mapping is indexed first by the token owner, then by an index specified in the nonce
                                /// @dev It returns a uint256 bitmap
                                /// @dev The index, or wordPosition is capped at type(uint248).max
                                function nonceBitmap(address, uint256) external view returns (uint256);
                                /// @notice Transfers a token using a signed permit message
                                /// @dev Reverts if the requested amount is greater than the permitted signed amount
                                /// @param permit The permit data signed over by the owner
                                /// @param owner The owner of the tokens to transfer
                                /// @param transferDetails The spender's requested transfer details for the permitted token
                                /// @param signature The signature to verify
                                function permitTransferFrom(
                                    PermitTransferFrom memory permit,
                                    SignatureTransferDetails calldata transferDetails,
                                    address owner,
                                    bytes calldata signature
                                ) external;
                                /// @notice Transfers a token using a signed permit message
                                /// @notice Includes extra data provided by the caller to verify signature over
                                /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
                                /// @dev Reverts if the requested amount is greater than the permitted signed amount
                                /// @param permit The permit data signed over by the owner
                                /// @param owner The owner of the tokens to transfer
                                /// @param transferDetails The spender's requested transfer details for the permitted token
                                /// @param witness Extra data to include when checking the user signature
                                /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
                                /// @param signature The signature to verify
                                function permitWitnessTransferFrom(
                                    PermitTransferFrom memory permit,
                                    SignatureTransferDetails calldata transferDetails,
                                    address owner,
                                    bytes32 witness,
                                    string calldata witnessTypeString,
                                    bytes calldata signature
                                ) external;
                                /// @notice Transfers multiple tokens using a signed permit message
                                /// @param permit The permit data signed over by the owner
                                /// @param owner The owner of the tokens to transfer
                                /// @param transferDetails Specifies the recipient and requested amount for the token transfer
                                /// @param signature The signature to verify
                                function permitTransferFrom(
                                    PermitBatchTransferFrom memory permit,
                                    SignatureTransferDetails[] calldata transferDetails,
                                    address owner,
                                    bytes calldata signature
                                ) external;
                                /// @notice Transfers multiple tokens using a signed permit message
                                /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
                                /// @notice Includes extra data provided by the caller to verify signature over
                                /// @param permit The permit data signed over by the owner
                                /// @param owner The owner of the tokens to transfer
                                /// @param transferDetails Specifies the recipient and requested amount for the token transfer
                                /// @param witness Extra data to include when checking the user signature
                                /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
                                /// @param signature The signature to verify
                                function permitWitnessTransferFrom(
                                    PermitBatchTransferFrom memory permit,
                                    SignatureTransferDetails[] calldata transferDetails,
                                    address owner,
                                    bytes32 witness,
                                    string calldata witnessTypeString,
                                    bytes calldata signature
                                ) external;
                                /// @notice Invalidates the bits specified in mask for the bitmap at the word position
                                /// @dev The wordPos is maxed at type(uint248).max
                                /// @param wordPos A number to index the nonceBitmap at
                                /// @param mask A bitmap masked against msg.sender's current bitmap at the word position
                                function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external;
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity ^0.8.17;
                            import {IAllowanceTransfer} from "../interfaces/IAllowanceTransfer.sol";
                            library Allowance {
                                // note if the expiration passed is 0, then it the approval set to the block.timestamp
                                uint256 private constant BLOCK_TIMESTAMP_EXPIRATION = 0;
                                /// @notice Sets the allowed amount, expiry, and nonce of the spender's permissions on owner's token.
                                /// @dev Nonce is incremented.
                                /// @dev If the inputted expiration is 0, the stored expiration is set to block.timestamp
                                function updateAll(
                                    IAllowanceTransfer.PackedAllowance storage allowed,
                                    uint160 amount,
                                    uint48 expiration,
                                    uint48 nonce
                                ) internal {
                                    uint48 storedNonce;
                                    unchecked {
                                        storedNonce = nonce + 1;
                                    }
                                    uint48 storedExpiration = expiration == BLOCK_TIMESTAMP_EXPIRATION ? uint48(block.timestamp) : expiration;
                                    uint256 word = pack(amount, storedExpiration, storedNonce);
                                    assembly {
                                        sstore(allowed.slot, word)
                                    }
                                }
                                /// @notice Sets the allowed amount and expiry of the spender's permissions on owner's token.
                                /// @dev Nonce does not need to be incremented.
                                function updateAmountAndExpiration(
                                    IAllowanceTransfer.PackedAllowance storage allowed,
                                    uint160 amount,
                                    uint48 expiration
                                ) internal {
                                    // If the inputted expiration is 0, the allowance only lasts the duration of the block.
                                    allowed.expiration = expiration == 0 ? uint48(block.timestamp) : expiration;
                                    allowed.amount = amount;
                                }
                                /// @notice Computes the packed slot of the amount, expiration, and nonce that make up PackedAllowance
                                function pack(uint160 amount, uint48 expiration, uint48 nonce) internal pure returns (uint256 word) {
                                    word = (uint256(nonce) << 208) | uint256(expiration) << 160 | amount;
                                }
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity ^0.8.17;
                            import {IAllowanceTransfer} from "../interfaces/IAllowanceTransfer.sol";
                            import {ISignatureTransfer} from "../interfaces/ISignatureTransfer.sol";
                            library PermitHash {
                                bytes32 public constant _PERMIT_DETAILS_TYPEHASH =
                                    keccak256("PermitDetails(address token,uint160 amount,uint48 expiration,uint48 nonce)");
                                bytes32 public constant _PERMIT_SINGLE_TYPEHASH = keccak256(
                                    "PermitSingle(PermitDetails details,address spender,uint256 sigDeadline)PermitDetails(address token,uint160 amount,uint48 expiration,uint48 nonce)"
                                );
                                bytes32 public constant _PERMIT_BATCH_TYPEHASH = keccak256(
                                    "PermitBatch(PermitDetails[] details,address spender,uint256 sigDeadline)PermitDetails(address token,uint160 amount,uint48 expiration,uint48 nonce)"
                                );
                                bytes32 public constant _TOKEN_PERMISSIONS_TYPEHASH = keccak256("TokenPermissions(address token,uint256 amount)");
                                bytes32 public constant _PERMIT_TRANSFER_FROM_TYPEHASH = keccak256(
                                    "PermitTransferFrom(TokenPermissions permitted,address spender,uint256 nonce,uint256 deadline)TokenPermissions(address token,uint256 amount)"
                                );
                                bytes32 public constant _PERMIT_BATCH_TRANSFER_FROM_TYPEHASH = keccak256(
                                    "PermitBatchTransferFrom(TokenPermissions[] permitted,address spender,uint256 nonce,uint256 deadline)TokenPermissions(address token,uint256 amount)"
                                );
                                string public constant _TOKEN_PERMISSIONS_TYPESTRING = "TokenPermissions(address token,uint256 amount)";
                                string public constant _PERMIT_TRANSFER_FROM_WITNESS_TYPEHASH_STUB =
                                    "PermitWitnessTransferFrom(TokenPermissions permitted,address spender,uint256 nonce,uint256 deadline,";
                                string public constant _PERMIT_BATCH_WITNESS_TRANSFER_FROM_TYPEHASH_STUB =
                                    "PermitBatchWitnessTransferFrom(TokenPermissions[] permitted,address spender,uint256 nonce,uint256 deadline,";
                                function hash(IAllowanceTransfer.PermitSingle memory permitSingle) internal pure returns (bytes32) {
                                    bytes32 permitHash = _hashPermitDetails(permitSingle.details);
                                    return
                                        keccak256(abi.encode(_PERMIT_SINGLE_TYPEHASH, permitHash, permitSingle.spender, permitSingle.sigDeadline));
                                }
                                function hash(IAllowanceTransfer.PermitBatch memory permitBatch) internal pure returns (bytes32) {
                                    uint256 numPermits = permitBatch.details.length;
                                    bytes32[] memory permitHashes = new bytes32[](numPermits);
                                    for (uint256 i = 0; i < numPermits; ++i) {
                                        permitHashes[i] = _hashPermitDetails(permitBatch.details[i]);
                                    }
                                    return keccak256(
                                        abi.encode(
                                            _PERMIT_BATCH_TYPEHASH,
                                            keccak256(abi.encodePacked(permitHashes)),
                                            permitBatch.spender,
                                            permitBatch.sigDeadline
                                        )
                                    );
                                }
                                function hash(ISignatureTransfer.PermitTransferFrom memory permit) internal view returns (bytes32) {
                                    bytes32 tokenPermissionsHash = _hashTokenPermissions(permit.permitted);
                                    return keccak256(
                                        abi.encode(_PERMIT_TRANSFER_FROM_TYPEHASH, tokenPermissionsHash, msg.sender, permit.nonce, permit.deadline)
                                    );
                                }
                                function hash(ISignatureTransfer.PermitBatchTransferFrom memory permit) internal view returns (bytes32) {
                                    uint256 numPermitted = permit.permitted.length;
                                    bytes32[] memory tokenPermissionHashes = new bytes32[](numPermitted);
                                    for (uint256 i = 0; i < numPermitted; ++i) {
                                        tokenPermissionHashes[i] = _hashTokenPermissions(permit.permitted[i]);
                                    }
                                    return keccak256(
                                        abi.encode(
                                            _PERMIT_BATCH_TRANSFER_FROM_TYPEHASH,
                                            keccak256(abi.encodePacked(tokenPermissionHashes)),
                                            msg.sender,
                                            permit.nonce,
                                            permit.deadline
                                        )
                                    );
                                }
                                function hashWithWitness(
                                    ISignatureTransfer.PermitTransferFrom memory permit,
                                    bytes32 witness,
                                    string calldata witnessTypeString
                                ) internal view returns (bytes32) {
                                    bytes32 typeHash = keccak256(abi.encodePacked(_PERMIT_TRANSFER_FROM_WITNESS_TYPEHASH_STUB, witnessTypeString));
                                    bytes32 tokenPermissionsHash = _hashTokenPermissions(permit.permitted);
                                    return keccak256(abi.encode(typeHash, tokenPermissionsHash, msg.sender, permit.nonce, permit.deadline, witness));
                                }
                                function hashWithWitness(
                                    ISignatureTransfer.PermitBatchTransferFrom memory permit,
                                    bytes32 witness,
                                    string calldata witnessTypeString
                                ) internal view returns (bytes32) {
                                    bytes32 typeHash =
                                        keccak256(abi.encodePacked(_PERMIT_BATCH_WITNESS_TRANSFER_FROM_TYPEHASH_STUB, witnessTypeString));
                                    uint256 numPermitted = permit.permitted.length;
                                    bytes32[] memory tokenPermissionHashes = new bytes32[](numPermitted);
                                    for (uint256 i = 0; i < numPermitted; ++i) {
                                        tokenPermissionHashes[i] = _hashTokenPermissions(permit.permitted[i]);
                                    }
                                    return keccak256(
                                        abi.encode(
                                            typeHash,
                                            keccak256(abi.encodePacked(tokenPermissionHashes)),
                                            msg.sender,
                                            permit.nonce,
                                            permit.deadline,
                                            witness
                                        )
                                    );
                                }
                                function _hashPermitDetails(IAllowanceTransfer.PermitDetails memory details) private pure returns (bytes32) {
                                    return keccak256(abi.encode(_PERMIT_DETAILS_TYPEHASH, details));
                                }
                                function _hashTokenPermissions(ISignatureTransfer.TokenPermissions memory permitted)
                                    private
                                    pure
                                    returns (bytes32)
                                {
                                    return keccak256(abi.encode(_TOKEN_PERMISSIONS_TYPEHASH, permitted));
                                }
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity ^0.8.17;
                            import {IERC1271} from "../interfaces/IERC1271.sol";
                            library SignatureVerification {
                                /// @notice Thrown when the passed in signature is not a valid length
                                error InvalidSignatureLength();
                                /// @notice Thrown when the recovered signer is equal to the zero address
                                error InvalidSignature();
                                /// @notice Thrown when the recovered signer does not equal the claimedSigner
                                error InvalidSigner();
                                /// @notice Thrown when the recovered contract signature is incorrect
                                error InvalidContractSignature();
                                bytes32 constant UPPER_BIT_MASK = (0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
                                function verify(bytes calldata signature, bytes32 hash, address claimedSigner) internal view {
                                    bytes32 r;
                                    bytes32 s;
                                    uint8 v;
                                    if (claimedSigner.code.length == 0) {
                                        if (signature.length == 65) {
                                            (r, s) = abi.decode(signature, (bytes32, bytes32));
                                            v = uint8(signature[64]);
                                        } else if (signature.length == 64) {
                                            // EIP-2098
                                            bytes32 vs;
                                            (r, vs) = abi.decode(signature, (bytes32, bytes32));
                                            s = vs & UPPER_BIT_MASK;
                                            v = uint8(uint256(vs >> 255)) + 27;
                                        } else {
                                            revert InvalidSignatureLength();
                                        }
                                        address signer = ecrecover(hash, v, r, s);
                                        if (signer == address(0)) revert InvalidSignature();
                                        if (signer != claimedSigner) revert InvalidSigner();
                                    } else {
                                        bytes4 magicValue = IERC1271(claimedSigner).isValidSignature(hash, signature);
                                        if (magicValue != IERC1271.isValidSignature.selector) revert InvalidContractSignature();
                                    }
                                }
                            }
                            

                            File 3 of 10: AdminUpgradeabilityProxy
                            // SPDX-License-Identifier: MIT
                            pragma solidity ^0.6.0;
                            import './UpgradeabilityProxy.sol';
                            /**
                             * @title AdminUpgradeabilityProxy
                             * @dev This contract combines an upgradeability proxy with an authorization
                             * mechanism for administrative tasks.
                             * All external functions in this contract must be guarded by the
                             * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
                             * feature proposal that would enable this to be done automatically.
                             */
                            contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
                              /**
                               * Contract constructor.
                               * @param _logic address of the initial implementation.
                               * @param _admin Address of the proxy administrator.
                               * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
                               * It should include the signature and the parameters of the function to be called, as described in
                               * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
                               * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
                               */
                              constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable {
                                assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
                                _setAdmin(_admin);
                              }
                              /**
                               * @dev Emitted when the administration has been transferred.
                               * @param previousAdmin Address of the previous admin.
                               * @param newAdmin Address of the new admin.
                               */
                              event AdminChanged(address previousAdmin, address newAdmin);
                              /**
                               * @dev Storage slot with the admin of the contract.
                               * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
                               * validated in the constructor.
                               */
                              bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
                              /**
                               * @dev Modifier to check whether the `msg.sender` is the admin.
                               * If it is, it will run the function. Otherwise, it will delegate the call
                               * to the implementation.
                               */
                              modifier ifAdmin() {
                                if (msg.sender == _admin()) {
                                  _;
                                } else {
                                  _fallback();
                                }
                              }
                              /**
                               * @return The address of the proxy admin.
                               */
                              function admin() external ifAdmin returns (address) {
                                return _admin();
                              }
                              /**
                               * @return The address of the implementation.
                               */
                              function implementation() external ifAdmin returns (address) {
                                return _implementation();
                              }
                              /**
                               * @dev Changes the admin of the proxy.
                               * Only the current admin can call this function.
                               * @param newAdmin Address to transfer proxy administration to.
                               */
                              function changeAdmin(address newAdmin) external ifAdmin {
                                require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
                                emit AdminChanged(_admin(), newAdmin);
                                _setAdmin(newAdmin);
                              }
                              /**
                               * @dev Upgrade the backing implementation of the proxy.
                               * Only the admin can call this function.
                               * @param newImplementation Address of the new implementation.
                               */
                              function upgradeTo(address newImplementation) external ifAdmin {
                                _upgradeTo(newImplementation);
                              }
                              /**
                               * @dev Upgrade the backing implementation of the proxy and call a function
                               * on the new implementation.
                               * This is useful to initialize the proxied contract.
                               * @param newImplementation Address of the new implementation.
                               * @param data Data to send as msg.data in the low level call.
                               * It should include the signature and the parameters of the function to be called, as described in
                               * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
                               */
                              function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
                                _upgradeTo(newImplementation);
                                (bool success,) = newImplementation.delegatecall(data);
                                require(success);
                              }
                              /**
                               * @return adm The admin slot.
                               */
                              function _admin() internal view returns (address adm) {
                                bytes32 slot = ADMIN_SLOT;
                                assembly {
                                  adm := sload(slot)
                                }
                              }
                              /**
                               * @dev Sets the address of the proxy admin.
                               * @param newAdmin Address of the new proxy admin.
                               */
                              function _setAdmin(address newAdmin) internal {
                                bytes32 slot = ADMIN_SLOT;
                                assembly {
                                  sstore(slot, newAdmin)
                                }
                              }
                              /**
                               * @dev Only fall back when the sender is not the admin.
                               */
                              function _willFallback() internal override virtual {
                                require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
                                super._willFallback();
                              }
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity ^0.6.0;
                            import './Proxy.sol';
                            import '@openzeppelin/contracts/utils/Address.sol';
                            /**
                             * @title UpgradeabilityProxy
                             * @dev This contract implements a proxy that allows to change the
                             * implementation address to which it will delegate.
                             * Such a change is called an implementation upgrade.
                             */
                            contract UpgradeabilityProxy is Proxy {
                              /**
                               * @dev Contract constructor.
                               * @param _logic Address of the initial implementation.
                               * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
                               * It should include the signature and the parameters of the function to be called, as described in
                               * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
                               * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
                               */
                              constructor(address _logic, bytes memory _data) public payable {
                                assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
                                _setImplementation(_logic);
                                if(_data.length > 0) {
                                  (bool success,) = _logic.delegatecall(_data);
                                  require(success);
                                }
                              }  
                              /**
                               * @dev Emitted when the implementation is upgraded.
                               * @param implementation Address of the new implementation.
                               */
                              event Upgraded(address indexed implementation);
                              /**
                               * @dev Storage slot with the address of the current implementation.
                               * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
                               * validated in the constructor.
                               */
                              bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                              /**
                               * @dev Returns the current implementation.
                               * @return impl Address of the current implementation
                               */
                              function _implementation() internal override view returns (address impl) {
                                bytes32 slot = IMPLEMENTATION_SLOT;
                                assembly {
                                  impl := sload(slot)
                                }
                              }
                              /**
                               * @dev Upgrades the proxy to a new implementation.
                               * @param newImplementation Address of the new implementation.
                               */
                              function _upgradeTo(address newImplementation) internal {
                                _setImplementation(newImplementation);
                                emit Upgraded(newImplementation);
                              }
                              /**
                               * @dev Sets the implementation address of the proxy.
                               * @param newImplementation Address of the new implementation.
                               */
                              function _setImplementation(address newImplementation) internal {
                                require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
                                bytes32 slot = IMPLEMENTATION_SLOT;
                                assembly {
                                  sstore(slot, newImplementation)
                                }
                              }
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity ^0.6.0;
                            /**
                             * @title Proxy
                             * @dev Implements delegation of calls to other contracts, with proper
                             * forwarding of return values and bubbling of failures.
                             * It defines a fallback function that delegates all calls to the address
                             * returned by the abstract _implementation() internal function.
                             */
                            abstract contract Proxy {
                              /**
                               * @dev Fallback function.
                               * Implemented entirely in `_fallback`.
                               */
                              fallback () payable external {
                                _fallback();
                              }
                              /**
                               * @dev Receive function.
                               * Implemented entirely in `_fallback`.
                               */
                              receive () payable external {
                                _fallback();
                              }
                              /**
                               * @return The Address of the implementation.
                               */
                              function _implementation() internal virtual view returns (address);
                              /**
                               * @dev Delegates execution to an implementation contract.
                               * This is a low level function that doesn't return to its internal call site.
                               * It will return to the external caller whatever the implementation returns.
                               * @param implementation Address to delegate.
                               */
                              function _delegate(address implementation) internal {
                                assembly {
                                  // Copy msg.data. We take full control of memory in this inline assembly
                                  // block because it will not return to Solidity code. We overwrite the
                                  // Solidity scratch pad at memory position 0.
                                  calldatacopy(0, 0, calldatasize())
                                  // Call the implementation.
                                  // out and outsize are 0 because we don't know the size yet.
                                  let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                                  // Copy the returned data.
                                  returndatacopy(0, 0, returndatasize())
                                  switch result
                                  // delegatecall returns 0 on error.
                                  case 0 { revert(0, returndatasize()) }
                                  default { return(0, returndatasize()) }
                                }
                              }
                              /**
                               * @dev Function that is run as the first thing in the fallback function.
                               * Can be redefined in derived contracts to add functionality.
                               * Redefinitions must call super._willFallback().
                               */
                              function _willFallback() internal virtual {
                              }
                              /**
                               * @dev fallback implementation.
                               * Extracted to enable manual triggering.
                               */
                              function _fallback() internal {
                                _willFallback();
                                _delegate(_implementation());
                              }
                            }
                            // SPDX-License-Identifier: MIT
                            pragma solidity >=0.6.2 <0.8.0;
                            /**
                             * @dev Collection of functions related to the address type
                             */
                            library Address {
                                /**
                                 * @dev Returns true if `account` is a contract.
                                 *
                                 * [IMPORTANT]
                                 * ====
                                 * It is unsafe to assume that an address for which this function returns
                                 * false is an externally-owned account (EOA) and not a contract.
                                 *
                                 * Among others, `isContract` will return false for the following
                                 * types of addresses:
                                 *
                                 *  - an externally-owned account
                                 *  - a contract in construction
                                 *  - an address where a contract will be created
                                 *  - an address where a contract lived, but was destroyed
                                 * ====
                                 */
                                function isContract(address account) internal view returns (bool) {
                                    // This method relies on extcodesize, which returns 0 for contracts in
                                    // construction, since the code is only stored at the end of the
                                    // constructor execution.
                                    uint256 size;
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly { size := extcodesize(account) }
                                    return size > 0;
                                }
                                /**
                                 * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                                 * `recipient`, forwarding all available gas and reverting on errors.
                                 *
                                 * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                                 * of certain opcodes, possibly making contracts go over the 2300 gas limit
                                 * imposed by `transfer`, making them unable to receive funds via
                                 * `transfer`. {sendValue} removes this limitation.
                                 *
                                 * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                                 *
                                 * IMPORTANT: because control is transferred to `recipient`, care must be
                                 * taken to not create reentrancy vulnerabilities. Consider using
                                 * {ReentrancyGuard} or the
                                 * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                                 */
                                function sendValue(address payable recipient, uint256 amount) internal {
                                    require(address(this).balance >= amount, "Address: insufficient balance");
                                    // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                                    (bool success, ) = recipient.call{ value: amount }("");
                                    require(success, "Address: unable to send value, recipient may have reverted");
                                }
                                /**
                                 * @dev Performs a Solidity function call using a low level `call`. A
                                 * plain`call` is an unsafe replacement for a function call: use this
                                 * function instead.
                                 *
                                 * If `target` reverts with a revert reason, it is bubbled up by this
                                 * function (like regular Solidity function calls).
                                 *
                                 * Returns the raw returned data. To convert to the expected return value,
                                 * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                                 *
                                 * Requirements:
                                 *
                                 * - `target` must be a contract.
                                 * - calling `target` with `data` must not revert.
                                 *
                                 * _Available since v3.1._
                                 */
                                function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                                  return functionCall(target, data, "Address: low-level call failed");
                                }
                                /**
                                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                                 * `errorMessage` as a fallback revert reason when `target` reverts.
                                 *
                                 * _Available since v3.1._
                                 */
                                function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                    return functionCallWithValue(target, data, 0, errorMessage);
                                }
                                /**
                                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                                 * but also transferring `value` wei to `target`.
                                 *
                                 * Requirements:
                                 *
                                 * - the calling contract must have an ETH balance of at least `value`.
                                 * - the called Solidity function must be `payable`.
                                 *
                                 * _Available since v3.1._
                                 */
                                function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                                    return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                                }
                                /**
                                 * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                                 * with `errorMessage` as a fallback revert reason when `target` reverts.
                                 *
                                 * _Available since v3.1._
                                 */
                                function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                                    require(address(this).balance >= value, "Address: insufficient balance for call");
                                    require(isContract(target), "Address: call to non-contract");
                                    // solhint-disable-next-line avoid-low-level-calls
                                    (bool success, bytes memory returndata) = target.call{ value: value }(data);
                                    return _verifyCallResult(success, returndata, errorMessage);
                                }
                                /**
                                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                                 * but performing a static call.
                                 *
                                 * _Available since v3.3._
                                 */
                                function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                    return functionStaticCall(target, data, "Address: low-level static call failed");
                                }
                                /**
                                 * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                                 * but performing a static call.
                                 *
                                 * _Available since v3.3._
                                 */
                                function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                                    require(isContract(target), "Address: static call to non-contract");
                                    // solhint-disable-next-line avoid-low-level-calls
                                    (bool success, bytes memory returndata) = target.staticcall(data);
                                    return _verifyCallResult(success, returndata, errorMessage);
                                }
                                function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                                    if (success) {
                                        return returndata;
                                    } else {
                                        // Look for revert reason and bubble it up if present
                                        if (returndata.length > 0) {
                                            // The easiest way to bubble the revert reason is using memory via assembly
                                            // solhint-disable-next-line no-inline-assembly
                                            assembly {
                                                let returndata_size := mload(returndata)
                                                revert(add(32, returndata), returndata_size)
                                            }
                                        } else {
                                            revert(errorMessage);
                                        }
                                    }
                                }
                            }
                            

                            File 4 of 10: UniswapV2Pair
                            // File: contracts/interfaces/IUniswapV2Pair.sol
                            
                            pragma solidity >=0.5.0;
                            
                            interface IUniswapV2Pair {
                                event Approval(address indexed owner, address indexed spender, uint value);
                                event Transfer(address indexed from, address indexed to, uint value);
                            
                                function name() external pure returns (string memory);
                                function symbol() external pure returns (string memory);
                                function decimals() external pure returns (uint8);
                                function totalSupply() external view returns (uint);
                                function balanceOf(address owner) external view returns (uint);
                                function allowance(address owner, address spender) external view returns (uint);
                            
                                function approve(address spender, uint value) external returns (bool);
                                function transfer(address to, uint value) external returns (bool);
                                function transferFrom(address from, address to, uint value) external returns (bool);
                            
                                function DOMAIN_SEPARATOR() external view returns (bytes32);
                                function PERMIT_TYPEHASH() external pure returns (bytes32);
                                function nonces(address owner) external view returns (uint);
                            
                                function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
                            
                                event Mint(address indexed sender, uint amount0, uint amount1);
                                event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                                event Swap(
                                    address indexed sender,
                                    uint amount0In,
                                    uint amount1In,
                                    uint amount0Out,
                                    uint amount1Out,
                                    address indexed to
                                );
                                event Sync(uint112 reserve0, uint112 reserve1);
                            
                                function MINIMUM_LIQUIDITY() external pure returns (uint);
                                function factory() external view returns (address);
                                function token0() external view returns (address);
                                function token1() external view returns (address);
                                function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
                                function price0CumulativeLast() external view returns (uint);
                                function price1CumulativeLast() external view returns (uint);
                                function kLast() external view returns (uint);
                            
                                function mint(address to) external returns (uint liquidity);
                                function burn(address to) external returns (uint amount0, uint amount1);
                                function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
                                function skim(address to) external;
                                function sync() external;
                            
                                function initialize(address, address) external;
                            }
                            
                            // File: contracts/interfaces/IUniswapV2ERC20.sol
                            
                            pragma solidity >=0.5.0;
                            
                            interface IUniswapV2ERC20 {
                                event Approval(address indexed owner, address indexed spender, uint value);
                                event Transfer(address indexed from, address indexed to, uint value);
                            
                                function name() external pure returns (string memory);
                                function symbol() external pure returns (string memory);
                                function decimals() external pure returns (uint8);
                                function totalSupply() external view returns (uint);
                                function balanceOf(address owner) external view returns (uint);
                                function allowance(address owner, address spender) external view returns (uint);
                            
                                function approve(address spender, uint value) external returns (bool);
                                function transfer(address to, uint value) external returns (bool);
                                function transferFrom(address from, address to, uint value) external returns (bool);
                            
                                function DOMAIN_SEPARATOR() external view returns (bytes32);
                                function PERMIT_TYPEHASH() external pure returns (bytes32);
                                function nonces(address owner) external view returns (uint);
                            
                                function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
                            }
                            
                            // File: contracts/libraries/SafeMath.sol
                            
                            pragma solidity =0.5.16;
                            
                            // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
                            
                            library SafeMath {
                                function add(uint x, uint y) internal pure returns (uint z) {
                                    require((z = x + y) >= x, 'ds-math-add-overflow');
                                }
                            
                                function sub(uint x, uint y) internal pure returns (uint z) {
                                    require((z = x - y) <= x, 'ds-math-sub-underflow');
                                }
                            
                                function mul(uint x, uint y) internal pure returns (uint z) {
                                    require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
                                }
                            }
                            
                            // File: contracts/UniswapV2ERC20.sol
                            
                            pragma solidity =0.5.16;
                            
                            
                            
                            contract UniswapV2ERC20 is IUniswapV2ERC20 {
                                using SafeMath for uint;
                            
                                string public constant name = 'Uniswap V2';
                                string public constant symbol = 'UNI-V2';
                                uint8 public constant decimals = 18;
                                uint  public totalSupply;
                                mapping(address => uint) public balanceOf;
                                mapping(address => mapping(address => uint)) public allowance;
                            
                                bytes32 public DOMAIN_SEPARATOR;
                                // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
                                bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                                mapping(address => uint) public nonces;
                            
                                event Approval(address indexed owner, address indexed spender, uint value);
                                event Transfer(address indexed from, address indexed to, uint value);
                            
                                constructor() public {
                                    uint chainId;
                                    assembly {
                                        chainId := chainid
                                    }
                                    DOMAIN_SEPARATOR = keccak256(
                                        abi.encode(
                                            keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
                                            keccak256(bytes(name)),
                                            keccak256(bytes('1')),
                                            chainId,
                                            address(this)
                                        )
                                    );
                                }
                            
                                function _mint(address to, uint value) internal {
                                    totalSupply = totalSupply.add(value);
                                    balanceOf[to] = balanceOf[to].add(value);
                                    emit Transfer(address(0), to, value);
                                }
                            
                                function _burn(address from, uint value) internal {
                                    balanceOf[from] = balanceOf[from].sub(value);
                                    totalSupply = totalSupply.sub(value);
                                    emit Transfer(from, address(0), value);
                                }
                            
                                function _approve(address owner, address spender, uint value) private {
                                    allowance[owner][spender] = value;
                                    emit Approval(owner, spender, value);
                                }
                            
                                function _transfer(address from, address to, uint value) private {
                                    balanceOf[from] = balanceOf[from].sub(value);
                                    balanceOf[to] = balanceOf[to].add(value);
                                    emit Transfer(from, to, value);
                                }
                            
                                function approve(address spender, uint value) external returns (bool) {
                                    _approve(msg.sender, spender, value);
                                    return true;
                                }
                            
                                function transfer(address to, uint value) external returns (bool) {
                                    _transfer(msg.sender, to, value);
                                    return true;
                                }
                            
                                function transferFrom(address from, address to, uint value) external returns (bool) {
                                    if (allowance[from][msg.sender] != uint(-1)) {
                                        allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                                    }
                                    _transfer(from, to, value);
                                    return true;
                                }
                            
                                function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
                                    require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
                                    bytes32 digest = keccak256(
                                        abi.encodePacked(
                                            '\x19\x01',
                                            DOMAIN_SEPARATOR,
                                            keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                                        )
                                    );
                                    address recoveredAddress = ecrecover(digest, v, r, s);
                                    require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
                                    _approve(owner, spender, value);
                                }
                            }
                            
                            // File: contracts/libraries/Math.sol
                            
                            pragma solidity =0.5.16;
                            
                            // a library for performing various math operations
                            
                            library Math {
                                function min(uint x, uint y) internal pure returns (uint z) {
                                    z = x < y ? x : y;
                                }
                            
                                // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
                                function sqrt(uint y) internal pure returns (uint z) {
                                    if (y > 3) {
                                        z = y;
                                        uint x = y / 2 + 1;
                                        while (x < z) {
                                            z = x;
                                            x = (y / x + x) / 2;
                                        }
                                    } else if (y != 0) {
                                        z = 1;
                                    }
                                }
                            }
                            
                            // File: contracts/libraries/UQ112x112.sol
                            
                            pragma solidity =0.5.16;
                            
                            // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
                            
                            // range: [0, 2**112 - 1]
                            // resolution: 1 / 2**112
                            
                            library UQ112x112 {
                                uint224 constant Q112 = 2**112;
                            
                                // encode a uint112 as a UQ112x112
                                function encode(uint112 y) internal pure returns (uint224 z) {
                                    z = uint224(y) * Q112; // never overflows
                                }
                            
                                // divide a UQ112x112 by a uint112, returning a UQ112x112
                                function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
                                    z = x / uint224(y);
                                }
                            }
                            
                            // File: contracts/interfaces/IERC20.sol
                            
                            pragma solidity >=0.5.0;
                            
                            interface IERC20 {
                                event Approval(address indexed owner, address indexed spender, uint value);
                                event Transfer(address indexed from, address indexed to, uint value);
                            
                                function name() external view returns (string memory);
                                function symbol() external view returns (string memory);
                                function decimals() external view returns (uint8);
                                function totalSupply() external view returns (uint);
                                function balanceOf(address owner) external view returns (uint);
                                function allowance(address owner, address spender) external view returns (uint);
                            
                                function approve(address spender, uint value) external returns (bool);
                                function transfer(address to, uint value) external returns (bool);
                                function transferFrom(address from, address to, uint value) external returns (bool);
                            }
                            
                            // File: contracts/interfaces/IUniswapV2Factory.sol
                            
                            pragma solidity >=0.5.0;
                            
                            interface IUniswapV2Factory {
                                event PairCreated(address indexed token0, address indexed token1, address pair, uint);
                            
                                function feeTo() external view returns (address);
                                function feeToSetter() external view returns (address);
                            
                                function getPair(address tokenA, address tokenB) external view returns (address pair);
                                function allPairs(uint) external view returns (address pair);
                                function allPairsLength() external view returns (uint);
                            
                                function createPair(address tokenA, address tokenB) external returns (address pair);
                            
                                function setFeeTo(address) external;
                                function setFeeToSetter(address) external;
                            }
                            
                            // File: contracts/interfaces/IUniswapV2Callee.sol
                            
                            pragma solidity >=0.5.0;
                            
                            interface IUniswapV2Callee {
                                function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
                            }
                            
                            // File: contracts/UniswapV2Pair.sol
                            
                            pragma solidity =0.5.16;
                            
                            
                            
                            
                            
                            
                            
                            
                            contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
                                using SafeMath  for uint;
                                using UQ112x112 for uint224;
                            
                                uint public constant MINIMUM_LIQUIDITY = 10**3;
                                bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
                            
                                address public factory;
                                address public token0;
                                address public token1;
                            
                                uint112 private reserve0;           // uses single storage slot, accessible via getReserves
                                uint112 private reserve1;           // uses single storage slot, accessible via getReserves
                                uint32  private blockTimestampLast; // uses single storage slot, accessible via getReserves
                            
                                uint public price0CumulativeLast;
                                uint public price1CumulativeLast;
                                uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
                            
                                uint private unlocked = 1;
                                modifier lock() {
                                    require(unlocked == 1, 'UniswapV2: LOCKED');
                                    unlocked = 0;
                                    _;
                                    unlocked = 1;
                                }
                            
                                function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
                                    _reserve0 = reserve0;
                                    _reserve1 = reserve1;
                                    _blockTimestampLast = blockTimestampLast;
                                }
                            
                                function _safeTransfer(address token, address to, uint value) private {
                                    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
                                    require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
                                }
                            
                                event Mint(address indexed sender, uint amount0, uint amount1);
                                event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                                event Swap(
                                    address indexed sender,
                                    uint amount0In,
                                    uint amount1In,
                                    uint amount0Out,
                                    uint amount1Out,
                                    address indexed to
                                );
                                event Sync(uint112 reserve0, uint112 reserve1);
                            
                                constructor() public {
                                    factory = msg.sender;
                                }
                            
                                // called once by the factory at time of deployment
                                function initialize(address _token0, address _token1) external {
                                    require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
                                    token0 = _token0;
                                    token1 = _token1;
                                }
                            
                                // update reserves and, on the first call per block, price accumulators
                                function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
                                    require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
                                    uint32 blockTimestamp = uint32(block.timestamp % 2**32);
                                    uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
                                    if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
                                        // * never overflows, and + overflow is desired
                                        price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
                                        price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
                                    }
                                    reserve0 = uint112(balance0);
                                    reserve1 = uint112(balance1);
                                    blockTimestampLast = blockTimestamp;
                                    emit Sync(reserve0, reserve1);
                                }
                            
                                // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
                                function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
                                    address feeTo = IUniswapV2Factory(factory).feeTo();
                                    feeOn = feeTo != address(0);
                                    uint _kLast = kLast; // gas savings
                                    if (feeOn) {
                                        if (_kLast != 0) {
                                            uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
                                            uint rootKLast = Math.sqrt(_kLast);
                                            if (rootK > rootKLast) {
                                                uint numerator = totalSupply.mul(rootK.sub(rootKLast));
                                                uint denominator = rootK.mul(5).add(rootKLast);
                                                uint liquidity = numerator / denominator;
                                                if (liquidity > 0) _mint(feeTo, liquidity);
                                            }
                                        }
                                    } else if (_kLast != 0) {
                                        kLast = 0;
                                    }
                                }
                            
                                // this low-level function should be called from a contract which performs important safety checks
                                function mint(address to) external lock returns (uint liquidity) {
                                    (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                    uint balance0 = IERC20(token0).balanceOf(address(this));
                                    uint balance1 = IERC20(token1).balanceOf(address(this));
                                    uint amount0 = balance0.sub(_reserve0);
                                    uint amount1 = balance1.sub(_reserve1);
                            
                                    bool feeOn = _mintFee(_reserve0, _reserve1);
                                    uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                                    if (_totalSupply == 0) {
                                        liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
                                       _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
                                    } else {
                                        liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
                                    }
                                    require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
                                    _mint(to, liquidity);
                            
                                    _update(balance0, balance1, _reserve0, _reserve1);
                                    if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                                    emit Mint(msg.sender, amount0, amount1);
                                }
                            
                                // this low-level function should be called from a contract which performs important safety checks
                                function burn(address to) external lock returns (uint amount0, uint amount1) {
                                    (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                    address _token0 = token0;                                // gas savings
                                    address _token1 = token1;                                // gas savings
                                    uint balance0 = IERC20(_token0).balanceOf(address(this));
                                    uint balance1 = IERC20(_token1).balanceOf(address(this));
                                    uint liquidity = balanceOf[address(this)];
                            
                                    bool feeOn = _mintFee(_reserve0, _reserve1);
                                    uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                                    amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
                                    amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
                                    require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
                                    _burn(address(this), liquidity);
                                    _safeTransfer(_token0, to, amount0);
                                    _safeTransfer(_token1, to, amount1);
                                    balance0 = IERC20(_token0).balanceOf(address(this));
                                    balance1 = IERC20(_token1).balanceOf(address(this));
                            
                                    _update(balance0, balance1, _reserve0, _reserve1);
                                    if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                                    emit Burn(msg.sender, amount0, amount1, to);
                                }
                            
                                // this low-level function should be called from a contract which performs important safety checks
                                function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
                                    require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
                                    (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                    require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
                            
                                    uint balance0;
                                    uint balance1;
                                    { // scope for _token{0,1}, avoids stack too deep errors
                                    address _token0 = token0;
                                    address _token1 = token1;
                                    require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
                                    if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
                                    if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
                                    if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
                                    balance0 = IERC20(_token0).balanceOf(address(this));
                                    balance1 = IERC20(_token1).balanceOf(address(this));
                                    }
                                    uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
                                    uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
                                    require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
                                    { // scope for reserve{0,1}Adjusted, avoids stack too deep errors
                                    uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
                                    uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
                                    require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
                                    }
                            
                                    _update(balance0, balance1, _reserve0, _reserve1);
                                    emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
                                }
                            
                                // force balances to match reserves
                                function skim(address to) external lock {
                                    address _token0 = token0; // gas savings
                                    address _token1 = token1; // gas savings
                                    _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
                                    _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
                                }
                            
                                // force reserves to match balances
                                function sync() external lock {
                                    _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
                                }
                            }

                            File 5 of 10: UniswapV2Pair
                            // File: contracts/interfaces/IUniswapV2Pair.sol
                            
                            pragma solidity >=0.5.0;
                            
                            interface IUniswapV2Pair {
                                event Approval(address indexed owner, address indexed spender, uint value);
                                event Transfer(address indexed from, address indexed to, uint value);
                            
                                function name() external pure returns (string memory);
                                function symbol() external pure returns (string memory);
                                function decimals() external pure returns (uint8);
                                function totalSupply() external view returns (uint);
                                function balanceOf(address owner) external view returns (uint);
                                function allowance(address owner, address spender) external view returns (uint);
                            
                                function approve(address spender, uint value) external returns (bool);
                                function transfer(address to, uint value) external returns (bool);
                                function transferFrom(address from, address to, uint value) external returns (bool);
                            
                                function DOMAIN_SEPARATOR() external view returns (bytes32);
                                function PERMIT_TYPEHASH() external pure returns (bytes32);
                                function nonces(address owner) external view returns (uint);
                            
                                function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
                            
                                event Mint(address indexed sender, uint amount0, uint amount1);
                                event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                                event Swap(
                                    address indexed sender,
                                    uint amount0In,
                                    uint amount1In,
                                    uint amount0Out,
                                    uint amount1Out,
                                    address indexed to
                                );
                                event Sync(uint112 reserve0, uint112 reserve1);
                            
                                function MINIMUM_LIQUIDITY() external pure returns (uint);
                                function factory() external view returns (address);
                                function token0() external view returns (address);
                                function token1() external view returns (address);
                                function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
                                function price0CumulativeLast() external view returns (uint);
                                function price1CumulativeLast() external view returns (uint);
                                function kLast() external view returns (uint);
                            
                                function mint(address to) external returns (uint liquidity);
                                function burn(address to) external returns (uint amount0, uint amount1);
                                function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
                                function skim(address to) external;
                                function sync() external;
                            
                                function initialize(address, address) external;
                            }
                            
                            // File: contracts/interfaces/IUniswapV2ERC20.sol
                            
                            pragma solidity >=0.5.0;
                            
                            interface IUniswapV2ERC20 {
                                event Approval(address indexed owner, address indexed spender, uint value);
                                event Transfer(address indexed from, address indexed to, uint value);
                            
                                function name() external pure returns (string memory);
                                function symbol() external pure returns (string memory);
                                function decimals() external pure returns (uint8);
                                function totalSupply() external view returns (uint);
                                function balanceOf(address owner) external view returns (uint);
                                function allowance(address owner, address spender) external view returns (uint);
                            
                                function approve(address spender, uint value) external returns (bool);
                                function transfer(address to, uint value) external returns (bool);
                                function transferFrom(address from, address to, uint value) external returns (bool);
                            
                                function DOMAIN_SEPARATOR() external view returns (bytes32);
                                function PERMIT_TYPEHASH() external pure returns (bytes32);
                                function nonces(address owner) external view returns (uint);
                            
                                function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
                            }
                            
                            // File: contracts/libraries/SafeMath.sol
                            
                            pragma solidity =0.5.16;
                            
                            // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
                            
                            library SafeMath {
                                function add(uint x, uint y) internal pure returns (uint z) {
                                    require((z = x + y) >= x, 'ds-math-add-overflow');
                                }
                            
                                function sub(uint x, uint y) internal pure returns (uint z) {
                                    require((z = x - y) <= x, 'ds-math-sub-underflow');
                                }
                            
                                function mul(uint x, uint y) internal pure returns (uint z) {
                                    require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
                                }
                            }
                            
                            // File: contracts/UniswapV2ERC20.sol
                            
                            pragma solidity =0.5.16;
                            
                            
                            
                            contract UniswapV2ERC20 is IUniswapV2ERC20 {
                                using SafeMath for uint;
                            
                                string public constant name = 'Uniswap V2';
                                string public constant symbol = 'UNI-V2';
                                uint8 public constant decimals = 18;
                                uint  public totalSupply;
                                mapping(address => uint) public balanceOf;
                                mapping(address => mapping(address => uint)) public allowance;
                            
                                bytes32 public DOMAIN_SEPARATOR;
                                // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
                                bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                                mapping(address => uint) public nonces;
                            
                                event Approval(address indexed owner, address indexed spender, uint value);
                                event Transfer(address indexed from, address indexed to, uint value);
                            
                                constructor() public {
                                    uint chainId;
                                    assembly {
                                        chainId := chainid
                                    }
                                    DOMAIN_SEPARATOR = keccak256(
                                        abi.encode(
                                            keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
                                            keccak256(bytes(name)),
                                            keccak256(bytes('1')),
                                            chainId,
                                            address(this)
                                        )
                                    );
                                }
                            
                                function _mint(address to, uint value) internal {
                                    totalSupply = totalSupply.add(value);
                                    balanceOf[to] = balanceOf[to].add(value);
                                    emit Transfer(address(0), to, value);
                                }
                            
                                function _burn(address from, uint value) internal {
                                    balanceOf[from] = balanceOf[from].sub(value);
                                    totalSupply = totalSupply.sub(value);
                                    emit Transfer(from, address(0), value);
                                }
                            
                                function _approve(address owner, address spender, uint value) private {
                                    allowance[owner][spender] = value;
                                    emit Approval(owner, spender, value);
                                }
                            
                                function _transfer(address from, address to, uint value) private {
                                    balanceOf[from] = balanceOf[from].sub(value);
                                    balanceOf[to] = balanceOf[to].add(value);
                                    emit Transfer(from, to, value);
                                }
                            
                                function approve(address spender, uint value) external returns (bool) {
                                    _approve(msg.sender, spender, value);
                                    return true;
                                }
                            
                                function transfer(address to, uint value) external returns (bool) {
                                    _transfer(msg.sender, to, value);
                                    return true;
                                }
                            
                                function transferFrom(address from, address to, uint value) external returns (bool) {
                                    if (allowance[from][msg.sender] != uint(-1)) {
                                        allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                                    }
                                    _transfer(from, to, value);
                                    return true;
                                }
                            
                                function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
                                    require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
                                    bytes32 digest = keccak256(
                                        abi.encodePacked(
                                            '\x19\x01',
                                            DOMAIN_SEPARATOR,
                                            keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                                        )
                                    );
                                    address recoveredAddress = ecrecover(digest, v, r, s);
                                    require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
                                    _approve(owner, spender, value);
                                }
                            }
                            
                            // File: contracts/libraries/Math.sol
                            
                            pragma solidity =0.5.16;
                            
                            // a library for performing various math operations
                            
                            library Math {
                                function min(uint x, uint y) internal pure returns (uint z) {
                                    z = x < y ? x : y;
                                }
                            
                                // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
                                function sqrt(uint y) internal pure returns (uint z) {
                                    if (y > 3) {
                                        z = y;
                                        uint x = y / 2 + 1;
                                        while (x < z) {
                                            z = x;
                                            x = (y / x + x) / 2;
                                        }
                                    } else if (y != 0) {
                                        z = 1;
                                    }
                                }
                            }
                            
                            // File: contracts/libraries/UQ112x112.sol
                            
                            pragma solidity =0.5.16;
                            
                            // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
                            
                            // range: [0, 2**112 - 1]
                            // resolution: 1 / 2**112
                            
                            library UQ112x112 {
                                uint224 constant Q112 = 2**112;
                            
                                // encode a uint112 as a UQ112x112
                                function encode(uint112 y) internal pure returns (uint224 z) {
                                    z = uint224(y) * Q112; // never overflows
                                }
                            
                                // divide a UQ112x112 by a uint112, returning a UQ112x112
                                function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
                                    z = x / uint224(y);
                                }
                            }
                            
                            // File: contracts/interfaces/IERC20.sol
                            
                            pragma solidity >=0.5.0;
                            
                            interface IERC20 {
                                event Approval(address indexed owner, address indexed spender, uint value);
                                event Transfer(address indexed from, address indexed to, uint value);
                            
                                function name() external view returns (string memory);
                                function symbol() external view returns (string memory);
                                function decimals() external view returns (uint8);
                                function totalSupply() external view returns (uint);
                                function balanceOf(address owner) external view returns (uint);
                                function allowance(address owner, address spender) external view returns (uint);
                            
                                function approve(address spender, uint value) external returns (bool);
                                function transfer(address to, uint value) external returns (bool);
                                function transferFrom(address from, address to, uint value) external returns (bool);
                            }
                            
                            // File: contracts/interfaces/IUniswapV2Factory.sol
                            
                            pragma solidity >=0.5.0;
                            
                            interface IUniswapV2Factory {
                                event PairCreated(address indexed token0, address indexed token1, address pair, uint);
                            
                                function feeTo() external view returns (address);
                                function feeToSetter() external view returns (address);
                            
                                function getPair(address tokenA, address tokenB) external view returns (address pair);
                                function allPairs(uint) external view returns (address pair);
                                function allPairsLength() external view returns (uint);
                            
                                function createPair(address tokenA, address tokenB) external returns (address pair);
                            
                                function setFeeTo(address) external;
                                function setFeeToSetter(address) external;
                            }
                            
                            // File: contracts/interfaces/IUniswapV2Callee.sol
                            
                            pragma solidity >=0.5.0;
                            
                            interface IUniswapV2Callee {
                                function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
                            }
                            
                            // File: contracts/UniswapV2Pair.sol
                            
                            pragma solidity =0.5.16;
                            
                            
                            
                            
                            
                            
                            
                            
                            contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
                                using SafeMath  for uint;
                                using UQ112x112 for uint224;
                            
                                uint public constant MINIMUM_LIQUIDITY = 10**3;
                                bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
                            
                                address public factory;
                                address public token0;
                                address public token1;
                            
                                uint112 private reserve0;           // uses single storage slot, accessible via getReserves
                                uint112 private reserve1;           // uses single storage slot, accessible via getReserves
                                uint32  private blockTimestampLast; // uses single storage slot, accessible via getReserves
                            
                                uint public price0CumulativeLast;
                                uint public price1CumulativeLast;
                                uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
                            
                                uint private unlocked = 1;
                                modifier lock() {
                                    require(unlocked == 1, 'UniswapV2: LOCKED');
                                    unlocked = 0;
                                    _;
                                    unlocked = 1;
                                }
                            
                                function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
                                    _reserve0 = reserve0;
                                    _reserve1 = reserve1;
                                    _blockTimestampLast = blockTimestampLast;
                                }
                            
                                function _safeTransfer(address token, address to, uint value) private {
                                    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
                                    require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
                                }
                            
                                event Mint(address indexed sender, uint amount0, uint amount1);
                                event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                                event Swap(
                                    address indexed sender,
                                    uint amount0In,
                                    uint amount1In,
                                    uint amount0Out,
                                    uint amount1Out,
                                    address indexed to
                                );
                                event Sync(uint112 reserve0, uint112 reserve1);
                            
                                constructor() public {
                                    factory = msg.sender;
                                }
                            
                                // called once by the factory at time of deployment
                                function initialize(address _token0, address _token1) external {
                                    require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
                                    token0 = _token0;
                                    token1 = _token1;
                                }
                            
                                // update reserves and, on the first call per block, price accumulators
                                function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
                                    require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
                                    uint32 blockTimestamp = uint32(block.timestamp % 2**32);
                                    uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
                                    if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
                                        // * never overflows, and + overflow is desired
                                        price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
                                        price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
                                    }
                                    reserve0 = uint112(balance0);
                                    reserve1 = uint112(balance1);
                                    blockTimestampLast = blockTimestamp;
                                    emit Sync(reserve0, reserve1);
                                }
                            
                                // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
                                function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
                                    address feeTo = IUniswapV2Factory(factory).feeTo();
                                    feeOn = feeTo != address(0);
                                    uint _kLast = kLast; // gas savings
                                    if (feeOn) {
                                        if (_kLast != 0) {
                                            uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
                                            uint rootKLast = Math.sqrt(_kLast);
                                            if (rootK > rootKLast) {
                                                uint numerator = totalSupply.mul(rootK.sub(rootKLast));
                                                uint denominator = rootK.mul(5).add(rootKLast);
                                                uint liquidity = numerator / denominator;
                                                if (liquidity > 0) _mint(feeTo, liquidity);
                                            }
                                        }
                                    } else if (_kLast != 0) {
                                        kLast = 0;
                                    }
                                }
                            
                                // this low-level function should be called from a contract which performs important safety checks
                                function mint(address to) external lock returns (uint liquidity) {
                                    (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                    uint balance0 = IERC20(token0).balanceOf(address(this));
                                    uint balance1 = IERC20(token1).balanceOf(address(this));
                                    uint amount0 = balance0.sub(_reserve0);
                                    uint amount1 = balance1.sub(_reserve1);
                            
                                    bool feeOn = _mintFee(_reserve0, _reserve1);
                                    uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                                    if (_totalSupply == 0) {
                                        liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
                                       _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
                                    } else {
                                        liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
                                    }
                                    require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
                                    _mint(to, liquidity);
                            
                                    _update(balance0, balance1, _reserve0, _reserve1);
                                    if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                                    emit Mint(msg.sender, amount0, amount1);
                                }
                            
                                // this low-level function should be called from a contract which performs important safety checks
                                function burn(address to) external lock returns (uint amount0, uint amount1) {
                                    (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                    address _token0 = token0;                                // gas savings
                                    address _token1 = token1;                                // gas savings
                                    uint balance0 = IERC20(_token0).balanceOf(address(this));
                                    uint balance1 = IERC20(_token1).balanceOf(address(this));
                                    uint liquidity = balanceOf[address(this)];
                            
                                    bool feeOn = _mintFee(_reserve0, _reserve1);
                                    uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                                    amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
                                    amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
                                    require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
                                    _burn(address(this), liquidity);
                                    _safeTransfer(_token0, to, amount0);
                                    _safeTransfer(_token1, to, amount1);
                                    balance0 = IERC20(_token0).balanceOf(address(this));
                                    balance1 = IERC20(_token1).balanceOf(address(this));
                            
                                    _update(balance0, balance1, _reserve0, _reserve1);
                                    if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                                    emit Burn(msg.sender, amount0, amount1, to);
                                }
                            
                                // this low-level function should be called from a contract which performs important safety checks
                                function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
                                    require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
                                    (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                    require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
                            
                                    uint balance0;
                                    uint balance1;
                                    { // scope for _token{0,1}, avoids stack too deep errors
                                    address _token0 = token0;
                                    address _token1 = token1;
                                    require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
                                    if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
                                    if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
                                    if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
                                    balance0 = IERC20(_token0).balanceOf(address(this));
                                    balance1 = IERC20(_token1).balanceOf(address(this));
                                    }
                                    uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
                                    uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
                                    require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
                                    { // scope for reserve{0,1}Adjusted, avoids stack too deep errors
                                    uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
                                    uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
                                    require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
                                    }
                            
                                    _update(balance0, balance1, _reserve0, _reserve1);
                                    emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
                                }
                            
                                // force balances to match reserves
                                function skim(address to) external lock {
                                    address _token0 = token0; // gas savings
                                    address _token1 = token1; // gas savings
                                    _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
                                    _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
                                }
                            
                                // force reserves to match balances
                                function sync() external lock {
                                    _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
                                }
                            }

                            File 6 of 10: Dai
                            // hevm: flattened sources of /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/dai.sol
                            pragma solidity =0.5.12;
                            
                            ////// /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/lib.sol
                            // 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.5.12; */
                            
                            contract LibNote {
                                event LogNote(
                                    bytes4   indexed  sig,
                                    address  indexed  usr,
                                    bytes32  indexed  arg1,
                                    bytes32  indexed  arg2,
                                    bytes             data
                                ) anonymous;
                            
                                modifier note {
                                    _;
                                    assembly {
                                        // log an 'anonymous' event with a constant 6 words of calldata
                                        // and four indexed topics: selector, caller, arg1 and arg2
                                        let mark := msize                         // end of memory ensures zero
                                        mstore(0x40, add(mark, 288))              // update free memory pointer
                                        mstore(mark, 0x20)                        // bytes type data offset
                                        mstore(add(mark, 0x20), 224)              // bytes size (padded)
                                        calldatacopy(add(mark, 0x40), 0, 224)     // bytes payload
                                        log4(mark, 288,                           // calldata
                                             shl(224, shr(224, calldataload(0))), // msg.sig
                                             caller,                              // msg.sender
                                             calldataload(4),                     // arg1
                                             calldataload(36)                     // arg2
                                            )
                                    }
                                }
                            }
                            
                            ////// /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/dai.sol
                            // Copyright (C) 2017, 2018, 2019 dbrock, rain, mrchico
                            
                            // This program is free software: you can redistribute it and/or modify
                            // it under the terms of the GNU Affero 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 Affero General Public License for more details.
                            //
                            // You should have received a copy of the GNU Affero General Public License
                            // along with this program.  If not, see <https://www.gnu.org/licenses/>.
                            
                            /* pragma solidity 0.5.12; */
                            
                            /* import "./lib.sol"; */
                            
                            contract Dai is LibNote {
                                // --- Auth ---
                                mapping (address => uint) public wards;
                                function rely(address guy) external note auth { wards[guy] = 1; }
                                function deny(address guy) external note auth { wards[guy] = 0; }
                                modifier auth {
                                    require(wards[msg.sender] == 1, "Dai/not-authorized");
                                    _;
                                }
                            
                                // --- ERC20 Data ---
                                string  public constant name     = "Dai Stablecoin";
                                string  public constant symbol   = "DAI";
                                string  public constant version  = "1";
                                uint8   public constant decimals = 18;
                                uint256 public totalSupply;
                            
                                mapping (address => uint)                      public balanceOf;
                                mapping (address => mapping (address => uint)) public allowance;
                                mapping (address => uint)                      public nonces;
                            
                                event Approval(address indexed src, address indexed guy, uint wad);
                                event Transfer(address indexed src, address indexed dst, uint wad);
                            
                                // --- Math ---
                                function add(uint x, uint y) internal pure returns (uint z) {
                                    require((z = x + y) >= x);
                                }
                                function sub(uint x, uint y) internal pure returns (uint z) {
                                    require((z = x - y) <= x);
                                }
                            
                                // --- EIP712 niceties ---
                                bytes32 public DOMAIN_SEPARATOR;
                                // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
                                bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
                            
                                constructor(uint256 chainId_) public {
                                    wards[msg.sender] = 1;
                                    DOMAIN_SEPARATOR = keccak256(abi.encode(
                                        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                        keccak256(bytes(name)),
                                        keccak256(bytes(version)),
                                        chainId_,
                                        address(this)
                                    ));
                                }
                            
                                // --- Token ---
                                function transfer(address dst, uint wad) external returns (bool) {
                                    return transferFrom(msg.sender, dst, wad);
                                }
                                function transferFrom(address src, address dst, uint wad)
                                    public returns (bool)
                                {
                                    require(balanceOf[src] >= wad, "Dai/insufficient-balance");
                                    if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
                                        require(allowance[src][msg.sender] >= wad, "Dai/insufficient-allowance");
                                        allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad);
                                    }
                                    balanceOf[src] = sub(balanceOf[src], wad);
                                    balanceOf[dst] = add(balanceOf[dst], wad);
                                    emit Transfer(src, dst, wad);
                                    return true;
                                }
                                function mint(address usr, uint wad) external auth {
                                    balanceOf[usr] = add(balanceOf[usr], wad);
                                    totalSupply    = add(totalSupply, wad);
                                    emit Transfer(address(0), usr, wad);
                                }
                                function burn(address usr, uint wad) external {
                                    require(balanceOf[usr] >= wad, "Dai/insufficient-balance");
                                    if (usr != msg.sender && allowance[usr][msg.sender] != uint(-1)) {
                                        require(allowance[usr][msg.sender] >= wad, "Dai/insufficient-allowance");
                                        allowance[usr][msg.sender] = sub(allowance[usr][msg.sender], wad);
                                    }
                                    balanceOf[usr] = sub(balanceOf[usr], wad);
                                    totalSupply    = sub(totalSupply, wad);
                                    emit Transfer(usr, address(0), wad);
                                }
                                function approve(address usr, uint wad) external returns (bool) {
                                    allowance[msg.sender][usr] = wad;
                                    emit Approval(msg.sender, usr, wad);
                                    return true;
                                }
                            
                                // --- Alias ---
                                function push(address usr, uint wad) external {
                                    transferFrom(msg.sender, usr, wad);
                                }
                                function pull(address usr, uint wad) external {
                                    transferFrom(usr, msg.sender, wad);
                                }
                                function move(address src, address dst, uint wad) external {
                                    transferFrom(src, dst, wad);
                                }
                            
                                // --- Approve by signature ---
                                function permit(address holder, address spender, uint256 nonce, uint256 expiry,
                                                bool allowed, uint8 v, bytes32 r, bytes32 s) external
                                {
                                    bytes32 digest =
                                        keccak256(abi.encodePacked(
                                            "\x19\x01",
                                            DOMAIN_SEPARATOR,
                                            keccak256(abi.encode(PERMIT_TYPEHASH,
                                                                 holder,
                                                                 spender,
                                                                 nonce,
                                                                 expiry,
                                                                 allowed))
                                    ));
                            
                                    require(holder != address(0), "Dai/invalid-address-0");
                                    require(holder == ecrecover(digest, v, r, s), "Dai/invalid-permit");
                                    require(expiry == 0 || now <= expiry, "Dai/permit-expired");
                                    require(nonce == nonces[holder]++, "Dai/invalid-nonce");
                                    uint wad = allowed ? uint(-1) : 0;
                                    allowance[holder][spender] = wad;
                                    emit Approval(holder, spender, wad);
                                }
                            }

                            File 7 of 10: FiatTokenProxy
                            pragma solidity ^0.4.24;
                            
                            // File: zos-lib/contracts/upgradeability/Proxy.sol
                            
                            /**
                             * @title Proxy
                             * @dev Implements delegation of calls to other contracts, with proper
                             * forwarding of return values and bubbling of failures.
                             * It defines a fallback function that delegates all calls to the address
                             * returned by the abstract _implementation() internal function.
                             */
                            contract Proxy {
                              /**
                               * @dev Fallback function.
                               * Implemented entirely in `_fallback`.
                               */
                              function () payable external {
                                _fallback();
                              }
                            
                              /**
                               * @return The Address of the implementation.
                               */
                              function _implementation() internal view returns (address);
                            
                              /**
                               * @dev Delegates execution to an implementation contract.
                               * This is a low level function that doesn't return to its internal call site.
                               * It will return to the external caller whatever the implementation returns.
                               * @param implementation Address to delegate.
                               */
                              function _delegate(address implementation) internal {
                                assembly {
                                  // Copy msg.data. We take full control of memory in this inline assembly
                                  // block because it will not return to Solidity code. We overwrite the
                                  // Solidity scratch pad at memory position 0.
                                  calldatacopy(0, 0, calldatasize)
                            
                                  // Call the implementation.
                                  // out and outsize are 0 because we don't know the size yet.
                                  let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
                            
                                  // Copy the returned data.
                                  returndatacopy(0, 0, returndatasize)
                            
                                  switch result
                                  // delegatecall returns 0 on error.
                                  case 0 { revert(0, returndatasize) }
                                  default { return(0, returndatasize) }
                                }
                              }
                            
                              /**
                               * @dev Function that is run as the first thing in the fallback function.
                               * Can be redefined in derived contracts to add functionality.
                               * Redefinitions must call super._willFallback().
                               */
                              function _willFallback() internal {
                              }
                            
                              /**
                               * @dev fallback implementation.
                               * Extracted to enable manual triggering.
                               */
                              function _fallback() internal {
                                _willFallback();
                                _delegate(_implementation());
                              }
                            }
                            
                            // File: openzeppelin-solidity/contracts/AddressUtils.sol
                            
                            /**
                             * Utility library of inline functions on addresses
                             */
                            library AddressUtils {
                            
                              /**
                               * Returns whether the target address is a contract
                               * @dev This function will return false if invoked during the constructor of a contract,
                               * as the code is not actually created until after the constructor finishes.
                               * @param addr address to check
                               * @return whether the target address is a contract
                               */
                              function isContract(address addr) internal view returns (bool) {
                                uint256 size;
                                // XXX Currently there is no better way to check if there is a contract in an address
                                // than to check the size of the code at that address.
                                // See https://ethereum.stackexchange.com/a/14016/36603
                                // for more details about how this works.
                                // TODO Check this again before the Serenity release, because all addresses will be
                                // contracts then.
                                // solium-disable-next-line security/no-inline-assembly
                                assembly { size := extcodesize(addr) }
                                return size > 0;
                              }
                            
                            }
                            
                            // File: zos-lib/contracts/upgradeability/UpgradeabilityProxy.sol
                            
                            /**
                             * @title UpgradeabilityProxy
                             * @dev This contract implements a proxy that allows to change the
                             * implementation address to which it will delegate.
                             * Such a change is called an implementation upgrade.
                             */
                            contract UpgradeabilityProxy is Proxy {
                              /**
                               * @dev Emitted when the implementation is upgraded.
                               * @param implementation Address of the new implementation.
                               */
                              event Upgraded(address implementation);
                            
                              /**
                               * @dev Storage slot with the address of the current implementation.
                               * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is
                               * validated in the constructor.
                               */
                              bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
                            
                              /**
                               * @dev Contract constructor.
                               * @param _implementation Address of the initial implementation.
                               */
                              constructor(address _implementation) public {
                                assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
                            
                                _setImplementation(_implementation);
                              }
                            
                              /**
                               * @dev Returns the current implementation.
                               * @return Address of the current implementation
                               */
                              function _implementation() internal view returns (address impl) {
                                bytes32 slot = IMPLEMENTATION_SLOT;
                                assembly {
                                  impl := sload(slot)
                                }
                              }
                            
                              /**
                               * @dev Upgrades the proxy to a new implementation.
                               * @param newImplementation Address of the new implementation.
                               */
                              function _upgradeTo(address newImplementation) internal {
                                _setImplementation(newImplementation);
                                emit Upgraded(newImplementation);
                              }
                            
                              /**
                               * @dev Sets the implementation address of the proxy.
                               * @param newImplementation Address of the new implementation.
                               */
                              function _setImplementation(address newImplementation) private {
                                require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
                            
                                bytes32 slot = IMPLEMENTATION_SLOT;
                            
                                assembly {
                                  sstore(slot, newImplementation)
                                }
                              }
                            }
                            
                            // File: zos-lib/contracts/upgradeability/AdminUpgradeabilityProxy.sol
                            
                            /**
                             * @title AdminUpgradeabilityProxy
                             * @dev This contract combines an upgradeability proxy with an authorization
                             * mechanism for administrative tasks.
                             * All external functions in this contract must be guarded by the
                             * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
                             * feature proposal that would enable this to be done automatically.
                             */
                            contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
                              /**
                               * @dev Emitted when the administration has been transferred.
                               * @param previousAdmin Address of the previous admin.
                               * @param newAdmin Address of the new admin.
                               */
                              event AdminChanged(address previousAdmin, address newAdmin);
                            
                              /**
                               * @dev Storage slot with the admin of the contract.
                               * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
                               * validated in the constructor.
                               */
                              bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
                            
                              /**
                               * @dev Modifier to check whether the `msg.sender` is the admin.
                               * If it is, it will run the function. Otherwise, it will delegate the call
                               * to the implementation.
                               */
                              modifier ifAdmin() {
                                if (msg.sender == _admin()) {
                                  _;
                                } else {
                                  _fallback();
                                }
                              }
                            
                              /**
                               * Contract constructor.
                               * It sets the `msg.sender` as the proxy administrator.
                               * @param _implementation address of the initial implementation.
                               */
                              constructor(address _implementation) UpgradeabilityProxy(_implementation) public {
                                assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
                            
                                _setAdmin(msg.sender);
                              }
                            
                              /**
                               * @return The address of the proxy admin.
                               */
                              function admin() external view ifAdmin returns (address) {
                                return _admin();
                              }
                            
                              /**
                               * @return The address of the implementation.
                               */
                              function implementation() external view ifAdmin returns (address) {
                                return _implementation();
                              }
                            
                              /**
                               * @dev Changes the admin of the proxy.
                               * Only the current admin can call this function.
                               * @param newAdmin Address to transfer proxy administration to.
                               */
                              function changeAdmin(address newAdmin) external ifAdmin {
                                require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
                                emit AdminChanged(_admin(), newAdmin);
                                _setAdmin(newAdmin);
                              }
                            
                              /**
                               * @dev Upgrade the backing implementation of the proxy.
                               * Only the admin can call this function.
                               * @param newImplementation Address of the new implementation.
                               */
                              function upgradeTo(address newImplementation) external ifAdmin {
                                _upgradeTo(newImplementation);
                              }
                            
                              /**
                               * @dev Upgrade the backing implementation of the proxy and call a function
                               * on the new implementation.
                               * This is useful to initialize the proxied contract.
                               * @param newImplementation Address of the new implementation.
                               * @param data Data to send as msg.data in the low level call.
                               * It should include the signature and the parameters of the function to be
                               * called, as described in
                               * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding.
                               */
                              function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin {
                                _upgradeTo(newImplementation);
                                require(address(this).call.value(msg.value)(data));
                              }
                            
                              /**
                               * @return The admin slot.
                               */
                              function _admin() internal view returns (address adm) {
                                bytes32 slot = ADMIN_SLOT;
                                assembly {
                                  adm := sload(slot)
                                }
                              }
                            
                              /**
                               * @dev Sets the address of the proxy admin.
                               * @param newAdmin Address of the new proxy admin.
                               */
                              function _setAdmin(address newAdmin) internal {
                                bytes32 slot = ADMIN_SLOT;
                            
                                assembly {
                                  sstore(slot, newAdmin)
                                }
                              }
                            
                              /**
                               * @dev Only fall back when the sender is not the admin.
                               */
                              function _willFallback() internal {
                                require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
                                super._willFallback();
                              }
                            }
                            
                            // File: contracts/FiatTokenProxy.sol
                            
                            /**
                            * Copyright CENTRE SECZ 2018
                            *
                            * Permission is hereby granted, free of charge, to any person obtaining a copy 
                            * of this software and associated documentation files (the "Software"), to deal 
                            * in the Software without restriction, including without limitation the rights 
                            * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
                            * copies of the Software, and to permit persons to whom the Software is furnished to 
                            * do so, subject to the following conditions:
                            *
                            * The above copyright notice and this permission notice shall be included in all 
                            * copies or substantial portions of the Software.
                            *
                            * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
                            * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
                            * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
                            * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
                            * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
                            * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                            */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            /**
                             * @title FiatTokenProxy
                             * @dev This contract proxies FiatToken calls and enables FiatToken upgrades
                            */ 
                            contract FiatTokenProxy is AdminUpgradeabilityProxy {
                                constructor(address _implementation) public AdminUpgradeabilityProxy(_implementation) {
                                }
                            }

                            File 8 of 10: UBI
                            // SPDX-License-Identifier: MIT
                            pragma solidity 0.7.3;
                            
                            /**
                             * This code contains elements of ERC20BurnableUpgradeable.sol https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/master/contracts/token/ERC20/ERC20BurnableUpgradeable.sol
                             * Those have been inlined for the purpose of gas optimization.
                             */
                            
                            
                            /**
                             * @dev Collection of functions related to the address type
                             */
                            library AddressUpgradeable {
                                /**
                                 * @dev Returns true if `account` is a contract.
                                 *
                                 * [IMPORTANT]
                                 * ====
                                 * It is unsafe to assume that an address for which this function returns
                                 * false is an externally-owned account (EOA) and not a contract.
                                 *
                                 * Among others, `isContract` will return false for the following
                                 * types of addresses:
                                 *
                                 *  - an externally-owned account
                                 *  - a contract in construction
                                 *  - an address where a contract will be created
                                 *  - an address where a contract lived, but was destroyed
                                 * ====
                                 */
                                function isContract(address account) internal view returns (bool) {
                                    // This method relies on extcodesize, which returns 0 for contracts in
                                    // construction, since the code is only stored at the end of the
                                    // constructor execution.
                            
                                    uint256 size;
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly { size := extcodesize(account) }
                                    return size > 0;
                                }
                            
                                /**
                                 * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                                 * `recipient`, forwarding all available gas and reverting on errors.
                                 *
                                 * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                                 * of certain opcodes, possibly making contracts go over the 2300 gas limit
                                 * imposed by `transfer`, making them unable to receive funds via
                                 * `transfer`. {sendValue} removes this limitation.
                                 *
                                 * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                                 *
                                 * IMPORTANT: because control is transferred to `recipient`, care must be
                                 * taken to not create reentrancy vulnerabilities. Consider using
                                 * {ReentrancyGuard} or the
                                 * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                                 */
                                function sendValue(address payable recipient, uint256 amount) internal {
                                    require(address(this).balance >= amount, "Address: insufficient balance");
                            
                                    // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                                    (bool success, ) = recipient.call{ value: amount }("");
                                    require(success, "Address: unable to send value, recipient may have reverted");
                                }
                            
                                /**
                                 * @dev Performs a Solidity function call using a low level `call`. A
                                 * plain`call` is an unsafe replacement for a function call: use this
                                 * function instead.
                                 *
                                 * If `target` reverts with a revert reason, it is bubbled up by this
                                 * function (like regular Solidity function calls).
                                 *
                                 * Returns the raw returned data. To convert to the expected return value,
                                 * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                                 *
                                 * Requirements:
                                 *
                                 * - `target` must be a contract.
                                 * - calling `target` with `data` must not revert.
                                 *
                                 * _Available since v3.1._
                                 */
                                function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                                  return functionCall(target, data, "Address: low-level call failed");
                                }
                            
                                /**
                                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                                 * `errorMessage` as a fallback revert reason when `target` reverts.
                                 *
                                 * _Available since v3.1._
                                 */
                                function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                    return functionCallWithValue(target, data, 0, errorMessage);
                                }
                            
                                /**
                                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                                 * but also transferring `value` wei to `target`.
                                 *
                                 * Requirements:
                                 *
                                 * - the calling contract must have an ETH balance of at least `value`.
                                 * - the called Solidity function must be `payable`.
                                 *
                                 * _Available since v3.1._
                                 */
                                function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                                    return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                                }
                            
                                /**
                                 * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                                 * with `errorMessage` as a fallback revert reason when `target` reverts.
                                 *
                                 * _Available since v3.1._
                                 */
                                function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                                    require(address(this).balance >= value, "Address: insufficient balance for call");
                                    require(isContract(target), "Address: call to non-contract");
                            
                                    // solhint-disable-next-line avoid-low-level-calls
                                    (bool success, bytes memory returndata) = target.call{ value: value }(data);
                                    return _verifyCallResult(success, returndata, errorMessage);
                                }
                            
                                /**
                                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                                 * but performing a static call.
                                 *
                                 * _Available since v3.3._
                                 */
                                function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                    return functionStaticCall(target, data, "Address: low-level static call failed");
                                }
                            
                                /**
                                 * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                                 * but performing a static call.
                                 *
                                 * _Available since v3.3._
                                 */
                                function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                                    require(isContract(target), "Address: static call to non-contract");
                            
                                    // solhint-disable-next-line avoid-low-level-calls
                                    (bool success, bytes memory returndata) = target.staticcall(data);
                                    return _verifyCallResult(success, returndata, errorMessage);
                                }
                            
                                function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                                    if (success) {
                                        return returndata;
                                    } else {
                                        // Look for revert reason and bubble it up if present
                                        if (returndata.length > 0) {
                                            // The easiest way to bubble the revert reason is using memory via assembly
                            
                                            // solhint-disable-next-line no-inline-assembly
                                            assembly {
                                                let returndata_size := mload(returndata)
                                                revert(add(32, returndata), returndata_size)
                                            }
                                        } else {
                                            revert(errorMessage);
                                        }
                                    }
                                }
                            }
                            
                            
                            
                            /**
                             * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
                             * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
                             * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
                             * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
                             *
                             * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
                             * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
                             *
                             * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
                             * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
                             */
                            abstract contract Initializable {
                            
                                /**
                                 * @dev Indicates that the contract has been initialized.
                                 */
                                bool private _initialized;
                            
                                /**
                                 * @dev Indicates that the contract is in the process of being initialized.
                                 */
                                bool private _initializing;
                            
                                /**
                                 * @dev Modifier to protect an initializer function from being invoked twice.
                                 */
                                modifier initializer() {
                                    require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
                            
                                    bool isTopLevelCall = !_initializing;
                                    if (isTopLevelCall) {
                                        _initializing = true;
                                        _initialized = true;
                                    }
                            
                                    _;
                            
                                    if (isTopLevelCall) {
                                        _initializing = false;
                                    }
                                }
                            
                                /// @dev Returns true if and only if the function is running in the constructor
                                function _isConstructor() private view returns (bool) {
                                    return !AddressUpgradeable.isContract(address(this));
                                }
                            }
                            
                            
                            
                            /**
                             * @dev Wrappers over Solidity's arithmetic operations with added overflow
                             * checks.
                             *
                             * Arithmetic operations in Solidity wrap on overflow. This can easily result
                             * in bugs, because programmers usually assume that an overflow raises an
                             * error, which is the standard behavior in high level programming languages.
                             * `SafeMath` restores this intuition by reverting the transaction when 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.
                             */
                            library SafeMath {
                                /**
                                 * @dev Returns the addition of two unsigned integers, with an overflow flag.
                                 *
                                 * _Available since v3.4._
                                 */
                                function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                    uint256 c = a + b;
                                    if (c < a) return (false, 0);
                                    return (true, c);
                                }
                            
                                /**
                                 * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                                 *
                                 * _Available since v3.4._
                                 */
                                function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                    if (b > a) return (false, 0);
                                    return (true, a - b);
                                }
                            
                                /**
                                 * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                                 *
                                 * _Available since v3.4._
                                 */
                                function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                    // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                                    // benefit is lost if 'b' is also tested.
                                    // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                                    if (a == 0) return (true, 0);
                                    uint256 c = a * b;
                                    if (c / a != b) return (false, 0);
                                    return (true, c);
                                }
                            
                                /**
                                 * @dev Returns the division of two unsigned integers, with a division by zero flag.
                                 *
                                 * _Available since v3.4._
                                 */
                                function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                    if (b == 0) return (false, 0);
                                    return (true, a / b);
                                }
                            
                                /**
                                 * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                                 *
                                 * _Available since v3.4._
                                 */
                                function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                    if (b == 0) return (false, 0);
                                    return (true, a % b);
                                }
                            
                                /**
                                 * @dev Returns the addition of two unsigned integers, reverting on
                                 * overflow.
                                 *
                                 * Counterpart to Solidity's `+` operator.
                                 *
                                 * Requirements:
                                 *
                                 * - Addition cannot overflow.
                                 */
                                function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                    uint256 c = a + b;
                                    require(c >= a, "SafeMath: addition overflow");
                                    return c;
                                }
                            
                                /**
                                 * @dev Returns the subtraction of two unsigned integers, reverting on
                                 * overflow (when the result is negative).
                                 *
                                 * Counterpart to Solidity's `-` operator.
                                 *
                                 * Requirements:
                                 *
                                 * - Subtraction cannot overflow.
                                 */
                                function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                    require(b <= a, "SafeMath: subtraction overflow");
                                    return a - b;
                                }
                            
                                /**
                                 * @dev Returns the multiplication of two unsigned integers, reverting on
                                 * overflow.
                                 *
                                 * Counterpart to Solidity's `*` operator.
                                 *
                                 * Requirements:
                                 *
                                 * - Multiplication cannot overflow.
                                 */
                                function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                    if (a == 0) return 0;
                                    uint256 c = a * b;
                                    require(c / a == b, "SafeMath: multiplication overflow");
                                    return c;
                                }
                            
                                /**
                                 * @dev Returns the integer division of two unsigned integers, reverting on
                                 * division by zero. The result is rounded towards zero.
                                 *
                                 * Counterpart to Solidity's `/` operator. Note: this function uses a
                                 * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                 * uses an invalid opcode to revert (consuming all remaining gas).
                                 *
                                 * Requirements:
                                 *
                                 * - The divisor cannot be zero.
                                 */
                                function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                    require(b > 0, "SafeMath: division by zero");
                                    return a / b;
                                }
                            
                                /**
                                 * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                 * reverting when dividing by zero.
                                 *
                                 * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                 * opcode (which leaves remaining gas untouched) while Solidity uses an
                                 * invalid opcode to revert (consuming all remaining gas).
                                 *
                                 * Requirements:
                                 *
                                 * - The divisor cannot be zero.
                                 */
                                function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                    require(b > 0, "SafeMath: modulo by zero");
                                    return a % b;
                                }
                            
                                /**
                                 * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                 * overflow (when the result is negative).
                                 *
                                 * CAUTION: This function is deprecated because it requires allocating memory for the error
                                 * message unnecessarily. For custom revert reasons use {trySub}.
                                 *
                                 * Counterpart to Solidity's `-` operator.
                                 *
                                 * Requirements:
                                 *
                                 * - Subtraction cannot overflow.
                                 */
                                function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                    require(b <= a, errorMessage);
                                    return a - b;
                                }
                            
                                /**
                                 * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                                 * division by zero. The result is rounded towards zero.
                                 *
                                 * CAUTION: This function is deprecated because it requires allocating memory for the error
                                 * message unnecessarily. For custom revert reasons use {tryDiv}.
                                 *
                                 * Counterpart to Solidity's `/` operator. Note: this function uses a
                                 * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                 * uses an invalid opcode to revert (consuming all remaining gas).
                                 *
                                 * Requirements:
                                 *
                                 * - The divisor cannot be zero.
                                 */
                                function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                    require(b > 0, errorMessage);
                                    return a / b;
                                }
                            
                                /**
                                 * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                 * reverting with custom message when dividing by zero.
                                 *
                                 * CAUTION: This function is deprecated because it requires allocating memory for the error
                                 * message unnecessarily. For custom revert reasons use {tryMod}.
                                 *
                                 * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                 * opcode (which leaves remaining gas untouched) while Solidity uses an
                                 * invalid opcode to revert (consuming all remaining gas).
                                 *
                                 * Requirements:
                                 *
                                 * - The divisor cannot be zero.
                                 */
                                function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                    require(b > 0, errorMessage);
                                    return a % b;
                                }
                            }
                            
                            
                            /**
                             * @title ProofOfHumanity Interface
                             * @dev See https://github.com/Proof-Of-Humanity/Proof-Of-Humanity.
                             */
                            interface IProofOfHumanity {
                              function isRegistered(address _submissionID)
                                external
                                view
                                returns (
                                  bool registered
                                );
                            }
                            
                            /**
                             * @title Universal Basic Income
                             * @dev UBI is an ERC20 compatible token that is connected to a Proof of Humanity registry. 
                             *
                             * Tokens are issued and drip over time for every verified submission on a Proof of Humanity registry.
                             * The accrued tokens are updated directly on every wallet using the `balanceOf` function.
                             * The tokens get effectively minted and persisted in memory when someone interacts with the contract doing a `transfer` or `burn`. 
                             */
                            contract UBI is Initializable {
                            
                              /* Events */
                              
                              /**
                               * @dev Emitted when `value` tokens are moved from one account (`from`) to another (`to`).
                               *
                               * Note that `value` may be zero.
                               * Also note that due to continuous minting we cannot emit transfer events from the address 0 when tokens are created.
                               * In order to keep consistency, we decided not to emit those events from the address 0 even when minting is done within a transaction.
                               */
                              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);
                            
                              using SafeMath for uint256;
                            
                              /* Storage */
                              
                              mapping (address => uint256) private balance;
                            
                              mapping (address => mapping (address => uint256)) public allowance;
                            
                              /// @dev A lower bound of the total supply. Does not take into account tokens minted as UBI by an address before it moves those (transfer or burn).
                              uint256 public totalSupply;
                              
                              /// @dev Name of the token.
                              string public name;
                              
                              /// @dev Symbol of the token.
                              string public symbol;
                              
                              /// @dev Number of decimals of the token.
                              uint8 public decimals;
                            
                              /// @dev How many tokens per second will be minted for every valid human.
                              uint256 public accruedPerSecond;
                            
                              /// @dev The contract's governor.
                              address public governor;
                              
                              /// @dev The Proof Of Humanity registry to reference.
                              IProofOfHumanity public proofOfHumanity; 
                            
                              /// @dev Timestamp since human started accruing.
                              mapping(address => uint256) public accruedSince;
                            
                              /* Modifiers */
                            
                              /// @dev Verifies that the sender has ability to modify governed parameters.
                              modifier onlyByGovernor() {
                                require(governor == msg.sender, "The caller is not the governor.");
                                _;
                              }
                            
                              /* Initializer */
                            
                              /** @dev Constructor.
                              *  @param _initialSupply for the UBI coin including all decimals.
                              *  @param _name for UBI coin.
                              *  @param _symbol for UBI coin ticker.
                              *  @param _accruedPerSecond How much of the token is accrued per block.
                              *  @param _proofOfHumanity The Proof Of Humanity registry to reference.
                              */
                              function initialize(uint256 _initialSupply, string memory _name, string memory _symbol, uint256 _accruedPerSecond, IProofOfHumanity _proofOfHumanity) public initializer {
                                name = _name;
                                symbol = _symbol;
                                decimals = 18;
                            
                                accruedPerSecond = _accruedPerSecond;
                                proofOfHumanity = _proofOfHumanity;
                                governor = msg.sender;
                            
                                balance[msg.sender] = _initialSupply;
                                totalSupply = _initialSupply;
                              }
                            
                              /* External */
                            
                              /** @dev Starts accruing UBI for a registered submission.
                              *  @param _human The submission ID.
                              */
                              function startAccruing(address _human) external {
                                require(proofOfHumanity.isRegistered(_human), "The submission is not registered in Proof Of Humanity.");
                                require(accruedSince[_human] == 0, "The submission is already accruing UBI.");
                                accruedSince[_human] = block.timestamp;
                              }
                            
                              /** @dev Allows anyone to report a submission that
                              *  should no longer receive UBI due to removal from the
                              *  Proof Of Humanity registry. The reporter receives any
                              *  leftover accrued UBI.
                              *  @param _human The submission ID.
                              */
                              function reportRemoval(address _human) external  {
                                require(!proofOfHumanity.isRegistered(_human), "The submission is still registered in Proof Of Humanity.");
                                require(accruedSince[_human] != 0, "The submission is not accruing UBI.");
                                uint256 newSupply = accruedPerSecond.mul(block.timestamp.sub(accruedSince[_human]));
                            
                                accruedSince[_human] = 0;
                            
                                balance[msg.sender] = balance[msg.sender].add(newSupply);
                                totalSupply = totalSupply.add(newSupply);
                              }
                            
                              /** @dev Changes `governor` to `_governor`.
                              *  @param _governor The address of the new governor.
                              */
                              function changeGovernor(address _governor) external onlyByGovernor {
                                governor = _governor;
                              }
                            
                              /** @dev Changes `proofOfHumanity` to `_proofOfHumanity`.
                              *  @param _proofOfHumanity Registry that meets interface of Proof of Humanity.
                              */
                              function changeProofOfHumanity(IProofOfHumanity _proofOfHumanity) external onlyByGovernor {
                                proofOfHumanity = _proofOfHumanity;
                              }
                            
                              /** @dev Transfers `_amount` to `_recipient` and withdraws accrued tokens.
                              *  @param _recipient The entity receiving the funds.
                              *  @param _amount The amount to tranfer in base units.
                              */
                              function transfer(address _recipient, uint256 _amount) public returns (bool) {
                                uint256 newSupplyFrom;
                                if (accruedSince[msg.sender] != 0 && proofOfHumanity.isRegistered(msg.sender)) {
                                    newSupplyFrom = accruedPerSecond.mul(block.timestamp.sub(accruedSince[msg.sender]));
                                    totalSupply = totalSupply.add(newSupplyFrom);
                                    accruedSince[msg.sender] = block.timestamp;
                                }
                                balance[msg.sender] = balance[msg.sender].add(newSupplyFrom).sub(_amount, "ERC20: transfer amount exceeds balance");
                                balance[_recipient] = balance[_recipient].add(_amount);
                                emit Transfer(msg.sender, _recipient, _amount);
                                return true;
                              }
                              
                              /** @dev Transfers `_amount` from `_sender` to `_recipient` and withdraws accrued tokens.
                              *  @param _sender The entity to take the funds from.
                              *  @param _recipient The entity receiving the funds.
                              *  @param _amount The amount to tranfer in base units.
                              */
                              function transferFrom(address _sender, address _recipient, uint256 _amount) public returns (bool) {
                                uint256 newSupplyFrom;
                                allowance[_sender][msg.sender] = allowance[_sender][msg.sender].sub(_amount, "ERC20: transfer amount exceeds allowance");
                                if (accruedSince[_sender] != 0 && proofOfHumanity.isRegistered(_sender)) {
                                    newSupplyFrom = accruedPerSecond.mul(block.timestamp.sub(accruedSince[_sender]));
                                    totalSupply = totalSupply.add(newSupplyFrom);
                                    accruedSince[_sender] = block.timestamp;
                                }
                                balance[_sender] = balance[_sender].add(newSupplyFrom).sub(_amount, "ERC20: transfer amount exceeds balance");
                                balance[_recipient] = balance[_recipient].add(_amount);       
                                emit Transfer(_sender, _recipient, _amount);
                                return true;
                              }
                            
                              /** @dev Approves `_spender` to spend `_amount`.
                              *  @param _spender The entity allowed to spend funds.
                              *  @param _amount The amount of base units the entity will be allowed to spend.
                              */
                              function approve(address _spender, uint256 _amount) public returns (bool) {
                                allowance[msg.sender][_spender] = _amount;
                                emit Approval(msg.sender, _spender, _amount);
                                return true;
                              }
                            
                              /** @dev Increases the `_spender` allowance by `_addedValue`.
                              *  @param _spender The entity allowed to spend funds.
                              *  @param _addedValue The amount of extra base units the entity will be allowed to spend.
                              */  
                              function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
                                uint256 newAllowance = allowance[msg.sender][_spender].add(_addedValue);
                                allowance[msg.sender][_spender] = newAllowance;
                                emit Approval(msg.sender, _spender, newAllowance);
                                return true;
                              }
                            
                              /** @dev Decreases the `_spender` allowance by `_subtractedValue`.
                              *  @param _spender The entity whose spending allocation will be reduced.
                              *  @param _subtractedValue The reduction of spending allocation in base units.
                              */  
                              function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
                                uint256 newAllowance = allowance[msg.sender][_spender].sub(_subtractedValue, "ERC20: decreased allowance below zero");
                                allowance[msg.sender][_spender] = newAllowance;
                                emit Approval(msg.sender, _spender, newAllowance);
                                return true;
                              }
                              
                              /** @dev Burns `_amount` of tokens and withdraws accrued tokens.
                              *  @param _amount The quantity of tokens to burn in base units.
                              */  
                              function burn(uint256 _amount) public {
                                uint256 newSupplyFrom;
                                if(accruedSince[msg.sender] != 0 && proofOfHumanity.isRegistered(msg.sender)) {
                                  newSupplyFrom = accruedPerSecond.mul(block.timestamp.sub(accruedSince[msg.sender]));
                                  accruedSince[msg.sender] = block.timestamp;
                                }
                                balance[msg.sender] = balance[msg.sender].add(newSupplyFrom).sub(_amount, "ERC20: burn amount exceeds balance");
                                totalSupply = totalSupply.add(newSupplyFrom).sub(_amount);
                                emit Transfer(msg.sender, address(0), _amount);
                              }
                            
                              /** @dev Burns `_amount` of tokens from `_account` and withdraws accrued tokens.
                              *  @param _account The entity to burn tokens from.
                              *  @param _amount The quantity of tokens to burn in base units.
                              */  
                              function burnFrom(address _account, uint256 _amount) public {
                                uint256 newSupplyFrom;
                                allowance[_account][msg.sender] = allowance[_account][msg.sender].sub(_amount, "ERC20: burn amount exceeds allowance");
                                if (accruedSince[_account] != 0 && proofOfHumanity.isRegistered(_account)) {
                                    newSupplyFrom = accruedPerSecond.mul(block.timestamp.sub(accruedSince[_account]));
                                    accruedSince[_account] = block.timestamp;
                                }
                                balance[_account] = balance[_account].add(newSupplyFrom).sub(_amount, "ERC20: burn amount exceeds balance");
                                totalSupply = totalSupply.add(newSupplyFrom).sub(_amount);
                                emit Transfer(_account, address(0), _amount);
                              }
                              
                              /* Getters */
                            
                              /** @dev Calculates how much UBI a submission has available for withdrawal.
                              *  @param _human The submission ID.
                              *  @return accrued The available UBI for withdrawal.
                              */
                              function getAccruedValue(address _human) public view returns (uint256 accrued) {
                                // If this human have not started to accrue, or is not registered, return 0.
                                if (accruedSince[_human] == 0 || !proofOfHumanity.isRegistered(_human)) return 0;
                            
                                else return accruedPerSecond.mul(block.timestamp.sub(accruedSince[_human]));
                              }
                              
                              /**
                              * @dev Calculates the current user accrued balance.
                              * @param _human The submission ID.
                              * @return The current balance including accrued Universal Basic Income of the user.
                              **/
                              function balanceOf(address _human) public view returns (uint256) {
                                return getAccruedValue(_human).add(balance[_human]);
                              }  
                            }

                            File 9 of 10: ProofOfHumanity
                            // File: https://github.com/kleros/ethereum-libraries/blob/39b54dec298117f9753d1a7dd2f08d596d26acdb/contracts/CappedMath.sol
                            
                            /**
                             *  @authors: [@mtsalenc]
                             *  @reviewers: [@clesaege]
                             *  @auditors: []
                             *  @bounties: []
                             *  @deployments: []
                             */
                            
                            pragma solidity ^0.5;
                            
                            
                            /**
                             * @title CappedMath
                             * @dev Math operations with caps for under and overflow.
                             */
                            library CappedMath {
                                uint constant private UINT_MAX = 2**256 - 1;
                                uint64 constant private UINT64_MAX = 2**64 - 1;
                            
                                /**
                                 * @dev Adds two unsigned integers, returns 2^256 - 1 on overflow.
                                 */
                                function addCap(uint _a, uint _b) internal pure returns (uint) {
                                    uint c = _a + _b;
                                    return c >= _a ? c : UINT_MAX;
                                }
                            
                                /**
                                 * @dev Subtracts two integers, returns 0 on underflow.
                                 */
                                function subCap(uint _a, uint _b) internal pure returns (uint) {
                                    if (_b > _a)
                                        return 0;
                                    else
                                        return _a - _b;
                                }
                            
                                /**
                                 * @dev Multiplies two unsigned integers, returns 2^256 - 1 on overflow.
                                 */
                                function mulCap(uint _a, uint _b) internal pure returns (uint) {
                                    // Gas optimization: this is cheaper than requiring '_a' not being zero, but the
                                    // benefit is lost if '_b' is also tested.
                                    // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                                    if (_a == 0)
                                        return 0;
                            
                                    uint c = _a * _b;
                                    return c / _a == _b ? c : UINT_MAX;
                                }
                            
                                function addCap64(uint64 _a, uint64 _b) internal pure returns (uint64) {
                                    uint64 c = _a + _b;
                                    return c >= _a ? c : UINT64_MAX;
                                }
                            
                            
                                function subCap64(uint64 _a, uint64 _b) internal pure returns (uint64) {
                                    if (_b > _a)
                                        return 0;
                                    else
                                        return _a - _b;
                                }
                            
                                function mulCap64(uint64 _a, uint64 _b) internal pure returns (uint64) {
                                    if (_a == 0)
                                        return 0;
                            
                                    uint64 c = _a * _b;
                                    return c / _a == _b ? c : UINT64_MAX;
                                }
                            }
                            
                            // File: https://github.com/kleros/erc-792/blob/c00f37dacdbf296e038bbaec9ad86c6a2f4b48d1/contracts/erc-1497/IEvidence.sol
                            
                            pragma solidity ^0.5;
                            
                            
                            /** @title IEvidence
                             *  ERC-1497: Evidence Standard
                             */
                            interface IEvidence {
                            
                                /** @dev To be emitted when meta-evidence is submitted.
                                 *  @param _metaEvidenceID Unique identifier of meta-evidence.
                                 *  @param _evidence A link to the meta-evidence JSON.
                                 */
                                event MetaEvidence(uint indexed _metaEvidenceID, string _evidence);
                            
                                /** @dev To be raised when evidence is submitted. Should point to the resource (evidences are not to be stored on chain due to gas considerations).
                                 *  @param _arbitrator The arbitrator of the contract.
                                 *  @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to.
                                 *  @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party.
                                 *  @param _evidence A URI to the evidence JSON file whose name should be its keccak256 hash followed by .json.
                                 */
                                event Evidence(IArbitrator indexed _arbitrator, uint indexed _evidenceGroupID, address indexed _party, string _evidence);
                            
                                /** @dev To be emitted when a dispute is created to link the correct meta-evidence to the disputeID.
                                 *  @param _arbitrator The arbitrator of the contract.
                                 *  @param _disputeID ID of the dispute in the Arbitrator contract.
                                 *  @param _metaEvidenceID Unique identifier of meta-evidence.
                                 *  @param _evidenceGroupID Unique identifier of the evidence group that is linked to this dispute.
                                 */
                                event Dispute(IArbitrator indexed _arbitrator, uint indexed _disputeID, uint _metaEvidenceID, uint _evidenceGroupID);
                            
                            }
                            
                            // File: https://github.com/kleros/erc-792/blob/c00f37dacdbf296e038bbaec9ad86c6a2f4b48d1/contracts/IArbitrator.sol
                            
                            /**
                             *  @title Arbitrator
                             *  @author Clément Lesaege - <clement@lesaege.com>
                             */
                            
                            pragma solidity ^0.5;
                            
                            
                            /** @title Arbitrator
                             *  Arbitrator abstract contract.
                             *  When developing arbitrator contracts we need to:
                             *  -Define the functions for dispute creation (createDispute) and appeal (appeal). Don't forget to store the arbitrated contract and the disputeID (which should be unique, may nbDisputes).
                             *  -Define the functions for cost display (arbitrationCost and appealCost).
                             *  -Allow giving rulings. For this a function must call arbitrable.rule(disputeID, ruling).
                             */
                            interface IArbitrator {
                            
                                enum DisputeStatus {Waiting, Appealable, Solved}
                            
                            
                                /** @dev To be emitted when a dispute is created.
                                 *  @param _disputeID ID of the dispute.
                                 *  @param _arbitrable The contract which created the dispute.
                                 */
                                event DisputeCreation(uint indexed _disputeID, IArbitrable indexed _arbitrable);
                            
                                /** @dev To be emitted when a dispute can be appealed.
                                 *  @param _disputeID ID of the dispute.
                                 */
                                event AppealPossible(uint indexed _disputeID, IArbitrable indexed _arbitrable);
                            
                                /** @dev To be emitted when the current ruling is appealed.
                                 *  @param _disputeID ID of the dispute.
                                 *  @param _arbitrable The contract which created the dispute.
                                 */
                                event AppealDecision(uint indexed _disputeID, IArbitrable indexed _arbitrable);
                            
                                /** @dev Create a dispute. Must be called by the arbitrable contract.
                                 *  Must be paid at least arbitrationCost(_extraData).
                                 *  @param _choices Amount of choices the arbitrator can make in this dispute.
                                 *  @param _extraData Can be used to give additional info on the dispute to be created.
                                 *  @return disputeID ID of the dispute created.
                                 */
                                function createDispute(uint _choices, bytes calldata _extraData) external payable returns(uint disputeID);
                            
                                /** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation.
                                 *  @param _extraData Can be used to give additional info on the dispute to be created.
                                 *  @return cost Amount to be paid.
                                 */
                                function arbitrationCost(bytes calldata _extraData) external view returns(uint cost);
                            
                                /** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule.
                                 *  @param _disputeID ID of the dispute to be appealed.
                                 *  @param _extraData Can be used to give extra info on the appeal.
                                 */
                                function appeal(uint _disputeID, bytes calldata _extraData) external payable;
                            
                                /** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation.
                                 *  @param _disputeID ID of the dispute to be appealed.
                                 *  @param _extraData Can be used to give additional info on the dispute to be created.
                                 *  @return cost Amount to be paid.
                                 */
                                function appealCost(uint _disputeID, bytes calldata _extraData) external view returns(uint cost);
                            
                                /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. If not known or appeal is impossible: should return (0, 0).
                                 *  @param _disputeID ID of the dispute.
                                 *  @return The start and end of the period.
                                 */
                                function appealPeriod(uint _disputeID) external view returns(uint start, uint end);
                            
                                /** @dev Return the status of a dispute.
                                 *  @param _disputeID ID of the dispute to rule.
                                 *  @return status The status of the dispute.
                                 */
                                function disputeStatus(uint _disputeID) external view returns(DisputeStatus status);
                            
                                /** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal.
                                 *  @param _disputeID ID of the dispute.
                                 *  @return ruling The ruling which has been given or the one which will be given if there is no appeal.
                                 */
                                function currentRuling(uint _disputeID) external view returns(uint ruling);
                            
                            }
                            
                            // File: https://github.com/kleros/erc-792/blob/c00f37dacdbf296e038bbaec9ad86c6a2f4b48d1/contracts/IArbitrable.sol
                            
                            /**
                             *  @title IArbitrable
                             *  @author Enrique Piqueras - <enrique@kleros.io>
                             */
                            
                            pragma solidity ^0.5;
                            
                            
                            /** @title IArbitrable
                             *  Arbitrable interface.
                             *  When developing arbitrable contracts, we need to:
                             *  -Define the action taken when a ruling is received by the contract.
                             *  -Allow dispute creation. For this a function must call arbitrator.createDispute.value(_fee)(_choices,_extraData);
                             */
                            interface IArbitrable {
                            
                                /** @dev To be raised when a ruling is given.
                                 *  @param _arbitrator The arbitrator giving the ruling.
                                 *  @param _disputeID ID of the dispute in the Arbitrator contract.
                                 *  @param _ruling The ruling which was given.
                                 */
                                event Ruling(IArbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling);
                            
                                /** @dev Give a ruling for a dispute. Must be called by the arbitrator.
                                 *  The purpose of this function is to ensure that the address calling it has the right to rule on the contract.
                                 *  @param _disputeID ID of the dispute in the Arbitrator contract.
                                 *  @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision".
                                 */
                                function rule(uint _disputeID, uint _ruling) external;
                            }
                            
                            // File: browser/github/Proof-Of-Humanity/Proof-Of-Humanity/contracts/ProofOfHumanity.sol
                            
                            /**
                             *  @authors: [@unknownunknown1, @nix1g]
                             *  @reviewers: [@fnanni-0*, @mtsalenc*, @nix1g*, @clesaege*, @hbarcelos*, @ferittuncer]
                             *  @auditors: []
                             *  @bounties: []
                             *  @deployments: []
                             *  @tools: [MythX*]
                             */
                            
                            pragma solidity ^0.5.13;
                            pragma experimental ABIEncoderV2;
                            
                            /**
                             *  @title ProofOfHumanity
                             *  This contract is a curated registry for people. The users are identified by their address and can be added or removed through the request-challenge protocol.
                             *  In order to challenge a registration request the challenger must provide one of the four reasons.
                             *  New registration requests firstly should gain sufficient amount of vouches from other registered users and only after that they can be accepted or challenged.
                             *  The users who vouched for submission that lost the challenge with the reason Duplicate or DoesNotExist would be penalized with optional fine or ban period.
                             *  NOTE: This contract trusts that the Arbitrator is honest and will not reenter or modify its costs during a call.
                             *  The arbitrator must support appeal period.
                             */
                            contract ProofOfHumanity is IArbitrable, IEvidence {
                                using CappedMath for uint;
                                using CappedMath for uint64;
                            
                                /* Constants and immutable */
                            
                                uint private constant RULING_OPTIONS = 2; // The amount of non 0 choices the arbitrator can give.
                                uint private constant AUTO_PROCESSED_VOUCH = 10; // The number of vouches that will be automatically processed when executing a request.
                                uint private constant FULL_REASONS_SET = 15; // Indicates that reasons' bitmap is full. 0b1111.
                                uint private constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers.
                            
                                bytes32 private DOMAIN_SEPARATOR; // The EIP-712 domainSeparator specific to this deployed instance. It is used to verify the IsHumanVoucher's signature.
                                bytes32 private constant IS_HUMAN_VOUCHER_TYPEHASH = 0xa9e3fa1df5c3dbef1e9cfb610fa780355a0b5e0acb0fa8249777ec973ca789dc; // The EIP-712 typeHash of IsHumanVoucher. keccak256("IsHumanVoucher(address vouchedSubmission,uint256 voucherExpirationTimestamp)").
                            
                                /* Enums */
                            
                                enum Status {
                                    None, // The submission doesn't have a pending status.
                                    Vouching, // The submission is in the state where it can be vouched for and crowdfunded.
                                    PendingRegistration, // The submission is in the state where it can be challenged. Or accepted to the list, if there are no challenges within the time limit.
                                    PendingRemoval // The submission is in the state where it can be challenged. Or removed from the list, if there are no challenges within the time limit.
                                }
                            
                                enum Party {
                                    None, // Party per default when there is no challenger or requester. Also used for unconclusive ruling.
                                    Requester, // Party that made the request to change a status.
                                    Challenger // Party that challenged the request to change a status.
                                }
                            
                                enum Reason {
                                    None, // No reason specified. This option should be used to challenge removal requests.
                                    IncorrectSubmission, // The submission does not comply with the submission rules.
                                    Deceased, // The submitter has existed but does not exist anymore.
                                    Duplicate, // The submitter is already registered. The challenger has to point to the identity already registered or to a duplicate submission.
                                    DoesNotExist // The submitter is not real. For example, this can be used for videos showing computer generated persons.
                                }
                            
                                /* Structs */
                            
                                struct Submission {
                                    Status status; // The current status of the submission.
                                    bool registered; // Whether the submission is in the registry or not. Note that a registered submission won't have privileges (e.g. vouching) if its duration expired.
                                    bool hasVouched; // True if this submission used its vouch for another submission. This is set back to false once the vouch is processed.
                                    uint64 submissionTime; // The time when the submission was accepted to the list.
                                    uint64 index; // Index of a submission.
                                    Request[] requests; // List of status change requests made for the submission.
                                }
                            
                                struct Request {
                                    bool disputed; // True if a dispute was raised. Note that the request can enter disputed state multiple times, once per reason.
                                    bool resolved; // True if the request is executed and/or all raised disputes are resolved.
                                    bool requesterLost; // True if the requester has already had a dispute that wasn't ruled in his favor.
                                    Reason currentReason; // Current reason a registration request was challenged with. Is left empty for removal requests.
                                    uint8 usedReasons; // Bitmap of the reasons used by challengers of this request.
                                    uint16 nbParallelDisputes; // Tracks the number of simultaneously raised disputes. Parallel disputes are only allowed for reason Duplicate.
                                    uint16 arbitratorDataID; // The index of the relevant arbitratorData struct. All the arbitrator info is stored in a separate struct to reduce gas cost.
                                    uint16 lastChallengeID; // The ID of the last challenge, which is equal to the total number of challenges for the request.
                                    uint32 lastProcessedVouch; // Stores the index of the last processed vouch in the array of vouches. It is used for partial processing of the vouches in resolved submissions.
                                    uint64 currentDuplicateIndex; // Stores the index of the duplicate submission provided by the challenger who is currently winning.
                                    uint64 challengePeriodStart; // Time when the submission can be challenged.
                                    address payable requester; // Address that made a request. It is left empty for the registration requests since it matches submissionID in that case.
                                    address payable ultimateChallenger; // Address of the challenger who won a dispute and who users that vouched for the request must pay the fines to.
                                    address[] vouches; // Stores the addresses of submissions that vouched for this request and whose vouches were used in this request.
                                    mapping(uint => Challenge) challenges; // Stores all the challenges of this request. challengeID -> Challenge.
                                    mapping(address => bool) challengeDuplicates; // Indicates whether a certain duplicate address has been used in a challenge or not.
                                }
                            
                                // Some arrays below have 3 elements to map with the Party enums for better readability:
                                // - 0: is unused, matches `Party.None`.
                                // - 1: for `Party.Requester`.
                                // - 2: for `Party.Challenger`.
                                struct Round {
                                    uint[3] paidFees; // Tracks the fees paid by each side in this round.
                                    Party sideFunded; // Stores the side that successfully paid the appeal fees in the latest round. Note that if both sides have paid a new round is created.
                                    uint feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute.
                                    mapping(address => uint[3]) contributions; // Maps contributors to their contributions for each side.
                                }
                            
                                struct Challenge {
                                    uint disputeID; // The ID of the dispute related to the challenge.
                                    Party ruling; // Ruling given by the arbitrator of the dispute.
                                    uint16 lastRoundID; // The ID of the last round.
                                    uint64 duplicateSubmissionIndex; // Index of a submission, which is a supposed duplicate of a challenged submission. It is only used for reason Duplicate.
                                    address payable challenger; // Address that challenged the request.
                                    mapping(uint => Round) rounds; // Tracks the info of each funding round of the challenge.
                                }
                            
                                // The data tied to the arbitrator that will be needed to recover the submission info for arbitrator's call.
                                struct DisputeData {
                                    uint96 challengeID; // The ID of the challenge of the request.
                                    address submissionID; // The submission, which ongoing request was challenged.
                                }
                            
                                struct ArbitratorData {
                                    IArbitrator arbitrator; // Address of the trusted arbitrator to solve disputes.
                                    uint96 metaEvidenceUpdates; // The meta evidence to be used in disputes.
                                    bytes arbitratorExtraData; // Extra data for the arbitrator.
                                }
                            
                                /* Storage */
                            
                                address public governor; // The address that can make governance changes to the parameters of the contract.
                            
                                uint public submissionBaseDeposit; // The base deposit to make a new request for a submission.
                            
                                // Note that to ensure correct contract behaviour the sum of challengePeriodDuration and renewalPeriodDuration should be less than submissionDuration.
                                uint64 public submissionDuration; // Time after which the registered submission will no longer be considered registered. The submitter has to reapply to the list to refresh it.
                                uint64 public renewalPeriodDuration; //  The duration of the period when the registered submission can reapply.
                                uint64 public challengePeriodDuration; // The time after which a request becomes executable if not challenged. Note that this value should be less than the time spent on potential dispute's resolution, to avoid complications of parallel dispute handling.
                            
                                uint64 public requiredNumberOfVouches; // The number of registered users that have to vouch for a new registration request in order for it to enter PendingRegistration state.
                            
                                uint public sharedStakeMultiplier; // Multiplier for calculating the fee stake that must be paid in the case where arbitrator refused to arbitrate.
                                uint public winnerStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that won the previous round.
                                uint public loserStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that lost the previous round.
                            
                                uint public submissionCounter; // The total count of all submissions that made a registration request at some point. Includes manually added submissions as well.
                            
                                ArbitratorData[] public arbitratorDataList; // Stores the arbitrator data of the contract. Updated each time the data is changed.
                            
                                mapping(address => Submission) private submissions; // Maps the submission ID to its data. submissions[submissionID]. It is private because of getSubmissionInfo().
                                mapping(address => mapping(address => bool)) public vouches; // Indicates whether or not the voucher has vouched for a certain submission. vouches[voucherID][submissionID].
                                mapping(address => mapping(uint => DisputeData)) public arbitratorDisputeIDToDisputeData; // Maps a dispute ID with its data. arbitratorDisputeIDToDisputeData[arbitrator][disputeID].
                            
                                /* Modifiers */
                            
                                modifier onlyGovernor {require(msg.sender == governor, "The caller must be the governor"); _;}
                            
                                /* Events */
                            
                                /**
                                 *  @dev Emitted when a vouch is added.
                                 *  @param _submissionID The submission that receives the vouch.
                                 *  @param _voucher The address that vouched.
                                 */
                                event VouchAdded(address indexed _submissionID, address indexed _voucher);
                            
                                /**
                                 *  @dev Emitted when a vouch is removed.
                                 *  @param _submissionID The submission which vouch is removed.
                                 *  @param _voucher The address that removes its vouch.
                                 */
                                event VouchRemoved(address indexed _submissionID, address indexed _voucher);
                            
                                /** @dev Emitted when the request to add a submission to the registry is made.
                                 *  @param _submissionID The ID of the submission.
                                 *  @param _requestID The ID of the newly created request.
                                 */
                                event AddSubmission(address indexed _submissionID, uint _requestID);
                            
                                /** @dev Emitted when the reapplication request is made.
                                 *  @param _submissionID The ID of the submission.
                                 *  @param _requestID The ID of the newly created request.
                                 */
                                event ReapplySubmission(address indexed _submissionID, uint _requestID);
                            
                                /** @dev Emitted when the removal request is made.
                                 *  @param _requester The address that made the request.
                                 *  @param _submissionID The ID of the submission.
                                 *  @param _requestID The ID of the newly created request.
                                 */
                                event RemoveSubmission(address indexed _requester, address indexed _submissionID, uint _requestID);
                            
                                /** @dev Emitted when the submission is challenged.
                                 *  @param _submissionID The ID of the submission.
                                 *  @param _requestID The ID of the latest request.
                                 *  @param _challengeID The ID of the challenge.
                                 */
                                event SubmissionChallenged(address indexed _submissionID, uint indexed _requestID, uint _challengeID);
                            
                                /** @dev To be emitted when someone contributes to the appeal process.
                                 *  @param _submissionID The ID of the submission.
                                 *  @param _challengeID The index of the challenge.
                                 *  @param _party The party which received the contribution.
                                 *  @param _contributor The address of the contributor.
                                 *  @param _amount The amount contributed.
                                 */
                                event AppealContribution(address indexed _submissionID, uint indexed _challengeID, Party _party, address indexed _contributor, uint _amount);
                            
                                /** @dev Emitted when one of the parties successfully paid its appeal fees.
                                 *  @param _submissionID The ID of the submission.
                                 *  @param _challengeID The index of the challenge which appeal was funded.
                                 *  @param _side The side that is fully funded.
                                 */
                                event HasPaidAppealFee(address indexed _submissionID, uint indexed _challengeID, Party _side);
                            
                                /** @dev Emitted when the challenge is resolved.
                                 *  @param _submissionID The ID of the submission.
                                 *  @param _requestID The ID of the latest request.
                                 *  @param _challengeID The ID of the challenge that was resolved.
                                 */
                                event ChallengeResolved(address indexed _submissionID, uint indexed _requestID, uint _challengeID);
                            
                                /** @dev Emitted in the constructor using most of its parameters.
                                 *  This event is needed for Subgraph. ArbitratorExtraData and renewalPeriodDuration are not needed for this event.
                                 */
                                event ArbitratorComplete(
                                    IArbitrator _arbitrator,
                                    address indexed _governor,
                                    uint _submissionBaseDeposit,
                                    uint _submissionDuration,
                                    uint _challengePeriodDuration,
                                    uint _requiredNumberOfVouches,
                                    uint _sharedStakeMultiplier,
                                    uint _winnerStakeMultiplier,
                                    uint _loserStakeMultiplier
                                );
                            
                                /** @dev Constructor.
                                 *  @param _arbitrator The trusted arbitrator to resolve potential disputes.
                                 *  @param _arbitratorExtraData Extra data for the trusted arbitrator contract.
                                 *  @param _registrationMetaEvidence The URI of the meta evidence object for registration requests.
                                 *  @param _clearingMetaEvidence The URI of the meta evidence object for clearing requests.
                                 *  @param _submissionBaseDeposit The base deposit to make a request for a submission.
                                 *  @param _submissionDuration Time in seconds during which the registered submission won't automatically lose its status.
                                 *  @param _renewalPeriodDuration Value that defines the duration of submission's renewal period.
                                 *  @param _challengePeriodDuration The time in seconds during which the request can be challenged.
                                 *  @param _multipliers The array that contains fee stake multipliers to avoid 'stack too deep' error.
                                 *  @param _requiredNumberOfVouches The number of vouches the submission has to have to pass from Vouching to PendingRegistration state.
                                 */
                                constructor(
                                    IArbitrator _arbitrator,
                                    bytes memory _arbitratorExtraData,
                                    string memory _registrationMetaEvidence,
                                    string memory _clearingMetaEvidence,
                                    uint _submissionBaseDeposit,
                                    uint64 _submissionDuration,
                                    uint64 _renewalPeriodDuration,
                                    uint64 _challengePeriodDuration,
                                    uint[3] memory _multipliers,
                                    uint64 _requiredNumberOfVouches
                                ) public {
                                    emit MetaEvidence(0, _registrationMetaEvidence);
                                    emit MetaEvidence(1, _clearingMetaEvidence);
                            
                                    governor = msg.sender;
                                    submissionBaseDeposit = _submissionBaseDeposit;
                                    submissionDuration = _submissionDuration;
                                    renewalPeriodDuration = _renewalPeriodDuration;
                                    challengePeriodDuration = _challengePeriodDuration;
                                    sharedStakeMultiplier = _multipliers[0];
                                    winnerStakeMultiplier = _multipliers[1];
                                    loserStakeMultiplier = _multipliers[2];
                                    requiredNumberOfVouches = _requiredNumberOfVouches;
                            
                                    ArbitratorData storage arbitratorData = arbitratorDataList[arbitratorDataList.length++];
                                    arbitratorData.arbitrator = _arbitrator;
                                    arbitratorData.arbitratorExtraData = _arbitratorExtraData;
                                    emit ArbitratorComplete(_arbitrator, msg.sender, _submissionBaseDeposit, _submissionDuration, _challengePeriodDuration, _requiredNumberOfVouches, _multipliers[0], _multipliers[1], _multipliers[2]);
                            
                                    // EIP-712.
                                    bytes32 DOMAIN_TYPEHASH = 0x8cad95687ba82c2ce50e74f7b754645e5117c3a5bec8151c0726d5857980a866; // keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)").
                                    uint256 chainId;
                                    assembly { chainId := chainid } // block.chainid got introduced in Solidity v0.8.0.
                                    DOMAIN_SEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256("Proof of Humanity"), chainId, address(this)));
                                }
                            
                                /* External and Public */
                            
                                // ************************ //
                                // *      Governance      * //
                                // ************************ //
                            
                                /** @dev Allows the governor to directly add new submissions to the list as a part of the seeding event.
                                 *  @param _submissionIDs The addresses of newly added submissions.
                                 *  @param _evidence The array of evidence links for each submission.
                                 *  @param _names The array of names of the submitters. This parameter is for Subgraph only and it won't be used in this function.
                                 */
                                function addSubmissionManually(address[] calldata _submissionIDs, string[] calldata _evidence, string[] calldata _names) external onlyGovernor {
                                    uint counter = submissionCounter;
                                    uint arbitratorDataID = arbitratorDataList.length - 1;
                                    for (uint i = 0; i < _submissionIDs.length; i++) {
                                        Submission storage submission = submissions[_submissionIDs[i]];
                                        require(submission.requests.length == 0, "Submission already been created");
                                        submission.index = uint64(counter);
                                        counter++;
                            
                                        Request storage request = submission.requests[submission.requests.length++];
                                        submission.registered = true;
                            
                                        submission.submissionTime = uint64(now);
                                        request.arbitratorDataID = uint16(arbitratorDataID);
                                        request.resolved = true;
                            
                                        if (bytes(_evidence[i]).length > 0)
                                            emit Evidence(arbitratorDataList[arbitratorDataID].arbitrator, uint(_submissionIDs[i]), msg.sender, _evidence[i]);
                                    }
                                    submissionCounter = counter;
                                }
                            
                                /** @dev Allows the governor to directly remove a registered entry from the list as a part of the seeding event.
                                 *  @param _submissionID The address of a submission to remove.
                                 */
                                function removeSubmissionManually(address _submissionID) external onlyGovernor {
                                    Submission storage submission = submissions[_submissionID];
                                    require(submission.registered && submission.status == Status.None, "Wrong status");
                                    submission.registered = false;
                                }
                            
                                /** @dev Change the base amount required as a deposit to make a request for a submission.
                                 *  @param _submissionBaseDeposit The new base amount of wei required to make a new request.
                                 */
                                function changeSubmissionBaseDeposit(uint _submissionBaseDeposit) external onlyGovernor {
                                    submissionBaseDeposit = _submissionBaseDeposit;
                                }
                            
                                /** @dev Change the duration of the submission, renewal and challenge periods.
                                 *  @param _submissionDuration The new duration of the time the submission is considered registered.
                                 *  @param _renewalPeriodDuration The new value that defines the duration of submission's renewal period.
                                 *  @param _challengePeriodDuration The new duration of the challenge period. It should be lower than the time for a dispute.
                                 */
                                function changeDurations(uint64 _submissionDuration, uint64 _renewalPeriodDuration, uint64 _challengePeriodDuration) external onlyGovernor {
                                    require(_challengePeriodDuration.addCap64(_renewalPeriodDuration) < _submissionDuration, "Incorrect inputs");
                                    submissionDuration = _submissionDuration;
                                    renewalPeriodDuration = _renewalPeriodDuration;
                                    challengePeriodDuration = _challengePeriodDuration;
                                }
                            
                                /** @dev Change the number of vouches required for the request to pass to the pending state.
                                 *  @param _requiredNumberOfVouches The new required number of vouches.
                                 */
                                function changeRequiredNumberOfVouches(uint64 _requiredNumberOfVouches) external onlyGovernor {
                                    requiredNumberOfVouches = _requiredNumberOfVouches;
                                }
                            
                                /** @dev Change the proportion of arbitration fees that must be paid as fee stake by parties when there is no winner or loser (e.g. when the arbitrator refused to rule).
                                 *  @param _sharedStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points.
                                 */
                                function changeSharedStakeMultiplier(uint _sharedStakeMultiplier) external onlyGovernor {
                                    sharedStakeMultiplier = _sharedStakeMultiplier;
                                }
                            
                                /** @dev Change the proportion of arbitration fees that must be paid as fee stake by the winner of the previous round.
                                 *  @param _winnerStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points.
                                 */
                                function changeWinnerStakeMultiplier(uint _winnerStakeMultiplier) external onlyGovernor {
                                    winnerStakeMultiplier = _winnerStakeMultiplier;
                                }
                            
                                /** @dev Change the proportion of arbitration fees that must be paid as fee stake by the party that lost the previous round.
                                 *  @param _loserStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points.
                                 */
                                function changeLoserStakeMultiplier(uint _loserStakeMultiplier) external onlyGovernor {
                                    loserStakeMultiplier = _loserStakeMultiplier;
                                }
                            
                                /** @dev Change the governor of the contract.
                                 *  @param _governor The address of the new governor.
                                 */
                                function changeGovernor(address _governor) external onlyGovernor {
                                    governor = _governor;
                                }
                            
                                /** @dev Update the meta evidence used for disputes.
                                 *  @param _registrationMetaEvidence The meta evidence to be used for future registration request disputes.
                                 *  @param _clearingMetaEvidence The meta evidence to be used for future clearing request disputes.
                                 */
                                function changeMetaEvidence(string calldata _registrationMetaEvidence, string calldata _clearingMetaEvidence) external onlyGovernor {
                                    ArbitratorData storage arbitratorData = arbitratorDataList[arbitratorDataList.length - 1];
                                    uint96 newMetaEvidenceUpdates = arbitratorData.metaEvidenceUpdates + 1;
                                    arbitratorDataList.push(ArbitratorData({
                                        arbitrator: arbitratorData.arbitrator,
                                        metaEvidenceUpdates: newMetaEvidenceUpdates,
                                        arbitratorExtraData: arbitratorData.arbitratorExtraData
                                    }));
                                    emit MetaEvidence(2 * newMetaEvidenceUpdates, _registrationMetaEvidence);
                                    emit MetaEvidence(2 * newMetaEvidenceUpdates + 1, _clearingMetaEvidence);
                                }
                            
                                /** @dev Change the arbitrator to be used for disputes that may be raised in the next requests. The arbitrator is trusted to support appeal period and not reenter.
                                 *  @param _arbitrator The new trusted arbitrator to be used in the next requests.
                                 *  @param _arbitratorExtraData The extra data used by the new arbitrator.
                                 */
                                function changeArbitrator(IArbitrator _arbitrator, bytes calldata _arbitratorExtraData) external onlyGovernor {
                                    ArbitratorData storage arbitratorData = arbitratorDataList[arbitratorDataList.length - 1];
                                    arbitratorDataList.push(ArbitratorData({
                                        arbitrator: _arbitrator,
                                        metaEvidenceUpdates: arbitratorData.metaEvidenceUpdates,
                                        arbitratorExtraData: _arbitratorExtraData
                                    }));
                                }
                            
                                // ************************ //
                                // *       Requests       * //
                                // ************************ //
                            
                                /** @dev Make a request to add a new entry to the list. Paying the full deposit right away is not required as it can be crowdfunded later.
                                 *  @param _evidence A link to evidence using its URI.
                                 *  @param _name The name of the submitter. This parameter is for Subgraph only and it won't be used in this function.
                                 */
                                function addSubmission(string calldata _evidence, string calldata _name) external payable {
                                    Submission storage submission = submissions[msg.sender];
                                    require(!submission.registered && submission.status == Status.None, "Wrong status");
                                    if (submission.requests.length == 0) {
                                        submission.index = uint64(submissionCounter);
                                        submissionCounter++;
                                    }
                                    submission.status = Status.Vouching;
                                    emit AddSubmission(msg.sender, submission.requests.length);
                                    requestRegistration(msg.sender, _evidence);
                                }
                            
                                /** @dev Make a request to refresh a submissionDuration. Paying the full deposit right away is not required as it can be crowdfunded later.
                                 *  Note that the user can reapply even when current submissionDuration has not expired, but only after the start of renewal period.
                                 *  @param _evidence A link to evidence using its URI.
                                 *  @param _name The name of the submitter. This parameter is for Subgraph only and it won't be used in this function.
                                 */
                                function reapplySubmission(string calldata _evidence, string calldata _name) external payable {
                                    Submission storage submission = submissions[msg.sender];
                                    require(submission.registered && submission.status == Status.None, "Wrong status");
                                    uint renewalAvailableAt = submission.submissionTime.addCap64(submissionDuration.subCap64(renewalPeriodDuration));
                                    require(now >= renewalAvailableAt, "Can't reapply yet");
                                    submission.status = Status.Vouching;
                                    emit ReapplySubmission(msg.sender, submission.requests.length);
                                    requestRegistration(msg.sender, _evidence);
                                }
                            
                                /** @dev Make a request to remove a submission from the list. Requires full deposit. Accepts enough ETH to cover the deposit, reimburses the rest.
                                 *  Note that this request can't be made during the renewal period to avoid spam leading to submission's expiration.
                                 *  @param _submissionID The address of the submission to remove.
                                 *  @param _evidence A link to evidence using its URI.
                                 */
                                function removeSubmission(address _submissionID, string calldata _evidence) external payable {
                                    Submission storage submission = submissions[_submissionID];
                                    require(submission.registered && submission.status == Status.None, "Wrong status");
                                    uint renewalAvailableAt = submission.submissionTime.addCap64(submissionDuration.subCap64(renewalPeriodDuration));
                                    require(now < renewalAvailableAt, "Can't remove after renewal");
                                    submission.status = Status.PendingRemoval;
                            
                                    Request storage request = submission.requests[submission.requests.length++];
                                    request.requester = msg.sender;
                                    request.challengePeriodStart = uint64(now);
                            
                                    uint arbitratorDataID = arbitratorDataList.length - 1;
                                    request.arbitratorDataID = uint16(arbitratorDataID);
                            
                                    Round storage round = request.challenges[0].rounds[0];
                            
                                    IArbitrator requestArbitrator = arbitratorDataList[arbitratorDataID].arbitrator;
                                    uint arbitrationCost = requestArbitrator.arbitrationCost(arbitratorDataList[arbitratorDataID].arbitratorExtraData);
                                    uint totalCost = arbitrationCost.addCap(submissionBaseDeposit);
                                    contribute(round, Party.Requester, msg.sender, msg.value, totalCost);
                            
                                    require(round.paidFees[uint(Party.Requester)] >= totalCost, "You must fully fund your side");
                                    round.sideFunded = Party.Requester;
                            
                                    emit RemoveSubmission(msg.sender, _submissionID, submission.requests.length - 1);
                            
                                    if (bytes(_evidence).length > 0)
                                        emit Evidence(requestArbitrator, submission.requests.length - 1 + uint(_submissionID), msg.sender, _evidence);
                                }
                            
                                /** @dev Fund the requester's deposit. Accepts enough ETH to cover the deposit, reimburses the rest.
                                 *  @param _submissionID The address of the submission which ongoing request to fund.
                                 */
                                function fundSubmission(address _submissionID) external payable {
                                    Submission storage submission = submissions[_submissionID];
                                    require(submission.status == Status.Vouching, "Wrong status");
                                    Request storage request = submission.requests[submission.requests.length - 1];
                                    Challenge storage challenge = request.challenges[0];
                                    Round storage round = challenge.rounds[0];
                            
                                    ArbitratorData storage arbitratorData = arbitratorDataList[request.arbitratorDataID];
                                    uint arbitrationCost = arbitratorData.arbitrator.arbitrationCost(arbitratorData.arbitratorExtraData);
                                    uint totalCost = arbitrationCost.addCap(submissionBaseDeposit);
                                    contribute(round, Party.Requester, msg.sender, msg.value, totalCost);
                            
                                    if (round.paidFees[uint(Party.Requester)] >= totalCost)
                                        round.sideFunded = Party.Requester;
                                }
                            
                                /** @dev Vouch for the submission. Note that the event spam is not an issue as it will be handled by the UI.
                                 *  @param _submissionID The address of the submission to vouch for.
                                 */
                                function addVouch(address _submissionID) external {
                                    vouches[msg.sender][_submissionID] = true;
                                    emit VouchAdded(_submissionID, msg.sender);
                                }
                            
                                /** @dev Remove the submission's vouch that has been added earlier. Note that the event spam is not an issue as it will be handled by the UI.
                                 *  @param _submissionID The address of the submission to remove vouch from.
                                 */
                                function removeVouch(address _submissionID) external {
                                    vouches[msg.sender][_submissionID] = false;
                                    emit VouchRemoved(_submissionID, msg.sender);
                                }
                            
                                /** @dev Allows to withdraw a mistakenly added submission while it's still in a vouching state.
                                 */
                                function withdrawSubmission() external {
                                    Submission storage submission = submissions[msg.sender];
                                    require(submission.status == Status.Vouching, "Wrong status");
                                    Request storage request = submission.requests[submission.requests.length - 1];
                            
                                    submission.status = Status.None;
                                    request.resolved = true;
                            
                                    withdrawFeesAndRewards(msg.sender, msg.sender, submission.requests.length - 1, 0, 0); // Automatically withdraw for the requester.
                                }
                            
                                /** @dev Change submission's state from Vouching to PendingRegistration if all conditions are met.
                                 *  @param _submissionID The address of the submission which status to change.
                                 *  @param _vouches Array of users whose vouches to count.
                                 *  @param _signatures Array of EIP-712 signatures of struct IsHumanVoucher (optional).
                                 *  @param _expirationTimestamps Array of expiration timestamps for each signature (optional).
                                 *  struct IsHumanVoucher {
                                 *      address vouchedSubmission;
                                 *      uint256 voucherExpirationTimestamp;
                                 *  }
                                 */
                                function changeStateToPending(address _submissionID, address[] calldata _vouches, bytes[] calldata _signatures, uint[] calldata _expirationTimestamps) external {
                                    Submission storage submission = submissions[_submissionID];
                                    require(submission.status == Status.Vouching, "Wrong status");
                                    Request storage request = submission.requests[submission.requests.length - 1];
                                    /* solium-disable indentation */
                                    {
                                        Challenge storage challenge = request.challenges[0];
                                        Round storage round = challenge.rounds[0];
                                        require(round.sideFunded == Party.Requester, "Requester is not funded");
                                    }
                                    /* solium-enable indentation */
                                    uint timeOffset = now - submissionDuration; // Precompute the offset before the loop for efficiency and then compare it with the submission time to check the expiration.
                            
                                    bytes2 PREFIX = "\x19\x01";
                                    for (uint i = 0; i < _signatures.length && request.vouches.length < requiredNumberOfVouches; i++) {
                                        address voucherAddress;
                                        /* solium-disable indentation */
                                        {
                                            // Get typed structure hash.
                                            bytes32 messageHash = keccak256(abi.encode(IS_HUMAN_VOUCHER_TYPEHASH, _submissionID, _expirationTimestamps[i]));
                                            bytes32 hash = keccak256(abi.encodePacked(PREFIX, DOMAIN_SEPARATOR, messageHash));
                            
                                            // Decode the signature.
                                            bytes memory signature = _signatures[i];
                                            bytes32 r;
                                            bytes32 s;
                                            uint8 v;
                                            assembly {
                                                r := mload(add(signature, 0x20))
                                                s := mload(add(signature, 0x40))
                                                v := byte(0, mload(add(signature, 0x60)))
                                            }
                                            if (v < 27) v += 27;
                                            require(v == 27 || v == 28, "Invalid signature");
                            
                                            // Recover the signer's address.
                                            voucherAddress = ecrecover(hash, v, r, s);
                                        }
                                        /* solium-enable indentation */
                            
                                        Submission storage voucher = submissions[voucherAddress];
                                        if (!voucher.hasVouched && voucher.registered && timeOffset <= voucher.submissionTime &&
                                        now < _expirationTimestamps[i] && _submissionID != voucherAddress) {
                                            request.vouches.push(voucherAddress);
                                            voucher.hasVouched = true;
                                            emit VouchAdded(_submissionID, voucherAddress);
                                        }
                                    }
                            
                                    for (uint i = 0; i<_vouches.length && request.vouches.length<requiredNumberOfVouches; i++) {
                                        // Check that the vouch isn't currently used by another submission and the voucher has a right to vouch.
                                        Submission storage voucher = submissions[_vouches[i]];
                                        if (!voucher.hasVouched && voucher.registered && timeOffset <= voucher.submissionTime &&
                                        vouches[_vouches[i]][_submissionID] && _submissionID != _vouches[i]) {
                                            request.vouches.push(_vouches[i]);
                                            voucher.hasVouched = true;
                                        }
                                    }
                                    require(request.vouches.length >= requiredNumberOfVouches, "Not enough valid vouches");
                                    submission.status = Status.PendingRegistration;
                                    request.challengePeriodStart = uint64(now);
                                }
                            
                                /** @dev Challenge the submission's request. Accepts enough ETH to cover the deposit, reimburses the rest.
                                 *  @param _submissionID The address of the submission which request to challenge.
                                 *  @param _reason The reason to challenge the request. Left empty for removal requests.
                                 *  @param _duplicateID The address of a supposed duplicate submission. Ignored if the reason is not Duplicate.
                                 *  @param _evidence A link to evidence using its URI. Ignored if not provided.
                                 */
                                function challengeRequest(address _submissionID, Reason _reason, address _duplicateID, string calldata _evidence) external payable {
                                    Submission storage submission = submissions[_submissionID];
                                    if (submission.status == Status.PendingRegistration)
                                        require(_reason != Reason.None, "Reason must be specified");
                                    else if (submission.status == Status.PendingRemoval)
                                        require(_reason == Reason.None, "Reason must be left empty");
                                    else
                                        revert("Wrong status");
                            
                                    Request storage request = submission.requests[submission.requests.length - 1];
                                    require(now - request.challengePeriodStart <= challengePeriodDuration, "Time to challenge has passed");
                            
                                    Challenge storage challenge = request.challenges[request.lastChallengeID];
                                    /* solium-disable indentation */
                                    {
                                        Reason currentReason = request.currentReason;
                                        if (_reason == Reason.Duplicate) {
                                            require(submissions[_duplicateID].status > Status.None || submissions[_duplicateID].registered, "Wrong duplicate status");
                                            require(_submissionID != _duplicateID, "Can't be a duplicate of itself");
                                            require(currentReason == Reason.Duplicate || currentReason == Reason.None, "Another reason is active");
                                            require(!request.challengeDuplicates[_duplicateID], "Duplicate address already used");
                                            request.challengeDuplicates[_duplicateID] = true;
                                            challenge.duplicateSubmissionIndex = submissions[_duplicateID].index;
                                        } else
                                            require(!request.disputed, "The request is disputed");
                            
                                        if (currentReason != _reason) {
                                            uint8 reasonBit = 1 << (uint8(_reason) - 1); // Get the bit that corresponds with reason's index.
                                            require((reasonBit & ~request.usedReasons) == reasonBit, "The reason has already been used");
                            
                                            request.usedReasons ^= reasonBit; // Mark the bit corresponding with reason's index as 'true', to indicate that the reason was used.
                                            request.currentReason = _reason;
                                        }
                                    }
                                    /* solium-enable indentation */
                            
                                    Round storage round = challenge.rounds[0];
                                    ArbitratorData storage arbitratorData = arbitratorDataList[request.arbitratorDataID];
                            
                                    uint arbitrationCost = arbitratorData.arbitrator.arbitrationCost(arbitratorData.arbitratorExtraData);
                                    contribute(round, Party.Challenger, msg.sender, msg.value, arbitrationCost);
                                    require(round.paidFees[uint(Party.Challenger)] >= arbitrationCost, "You must fully fund your side");
                                    round.feeRewards = round.feeRewards.subCap(arbitrationCost);
                                    round.sideFunded = Party.None; // Set this back to 0, since it's no longer relevant as the new round is created.
                            
                                    challenge.disputeID = arbitratorData.arbitrator.createDispute.value(arbitrationCost)(RULING_OPTIONS, arbitratorData.arbitratorExtraData);
                                    challenge.challenger = msg.sender;
                            
                                    DisputeData storage disputeData = arbitratorDisputeIDToDisputeData[address(arbitratorData.arbitrator)][challenge.disputeID];
                                    disputeData.challengeID = uint96(request.lastChallengeID);
                                    disputeData.submissionID = _submissionID;
                            
                                    request.disputed = true;
                                    request.nbParallelDisputes++;
                            
                                    challenge.lastRoundID++;
                                    emit SubmissionChallenged(_submissionID, submission.requests.length - 1, disputeData.challengeID);
                            
                                    request.lastChallengeID++;
                            
                                    emit Dispute(
                                        arbitratorData.arbitrator,
                                        challenge.disputeID,
                                        submission.status == Status.PendingRegistration ? 2 * arbitratorData.metaEvidenceUpdates : 2 * arbitratorData.metaEvidenceUpdates + 1,
                                        submission.requests.length - 1 + uint(_submissionID)
                                    );
                            
                                    if (bytes(_evidence).length > 0)
                                        emit Evidence(arbitratorData.arbitrator, submission.requests.length - 1 + uint(_submissionID), msg.sender, _evidence);
                                }
                            
                                /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if both sides are fully funded.
                                 *  @param _submissionID The address of the submission which request to fund.
                                 *  @param _challengeID The index of a dispute, created for the request.
                                 *  @param _side The recipient of the contribution.
                                 */
                                function fundAppeal(address _submissionID, uint _challengeID, Party _side) external payable {
                                    require(_side != Party.None); // You can only fund either requester or challenger.
                                    Submission storage submission = submissions[_submissionID];
                                    require(submission.status == Status.PendingRegistration || submission.status == Status.PendingRemoval, "Wrong status");
                                    Request storage request = submission.requests[submission.requests.length - 1];
                                    require(request.disputed, "No dispute to appeal");
                                    require(_challengeID < request.lastChallengeID, "Challenge out of bounds");
                            
                                    Challenge storage challenge = request.challenges[_challengeID];
                                    ArbitratorData storage arbitratorData = arbitratorDataList[request.arbitratorDataID];
                            
                                    (uint appealPeriodStart, uint appealPeriodEnd) = arbitratorData.arbitrator.appealPeriod(challenge.disputeID);
                                    require(now >= appealPeriodStart && now < appealPeriodEnd, "Appeal period is over");
                            
                                    uint multiplier;
                                    /* solium-disable indentation */
                                    {
                                        Party winner = Party(arbitratorData.arbitrator.currentRuling(challenge.disputeID));
                                        if (winner == _side){
                                            multiplier = winnerStakeMultiplier;
                                        } else if (winner == Party.None){
                                            multiplier = sharedStakeMultiplier;
                                        } else {
                                            multiplier = loserStakeMultiplier;
                                            require(now-appealPeriodStart < (appealPeriodEnd-appealPeriodStart)/2, "Appeal period is over for loser");
                                        }
                                    }
                                    /* solium-enable indentation */
                            
                                    Round storage round = challenge.rounds[challenge.lastRoundID];
                                    require(_side != round.sideFunded, "Side is already funded");
                            
                                    uint appealCost = arbitratorData.arbitrator.appealCost(challenge.disputeID, arbitratorData.arbitratorExtraData);
                                    uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR);
                                    uint contribution = contribute(round, _side, msg.sender, msg.value, totalCost);
                                    emit AppealContribution(_submissionID, _challengeID, _side, msg.sender, contribution);
                            
                                    if (round.paidFees[uint(_side)] >= totalCost) {
                                        if (round.sideFunded == Party.None) {
                                            round.sideFunded = _side;
                                        } else {
                                            // Both sides are fully funded. Create an appeal.
                                            arbitratorData.arbitrator.appeal.value(appealCost)(challenge.disputeID, arbitratorData.arbitratorExtraData);
                                            challenge.lastRoundID++;
                                            round.feeRewards = round.feeRewards.subCap(appealCost);
                                            round.sideFunded = Party.None; // Set this back to default in the past round as it's no longer relevant.
                                        }
                                        emit HasPaidAppealFee(_submissionID, _challengeID, _side);
                                    }
                                }
                            
                                /** @dev Execute a request if the challenge period passed and no one challenged the request.
                                 *  @param _submissionID The address of the submission with the request to execute.
                                 */
                                function executeRequest(address _submissionID) external {
                                    Submission storage submission = submissions[_submissionID];
                                    uint requestID = submission.requests.length - 1;
                                    Request storage request = submission.requests[requestID];
                                    require(now - request.challengePeriodStart > challengePeriodDuration, "Can't execute yet");
                                    require(!request.disputed, "The request is disputed");
                                    address payable requester;
                                    if (submission.status == Status.PendingRegistration) {
                                        // It is possible for the requester to lose without a dispute if he was penalized for bad vouching while reapplying.
                                        if (!request.requesterLost) {
                                            submission.registered = true;
                                            submission.submissionTime = uint64(now);
                                        }
                                        requester = address(uint160(_submissionID));
                                    } else if (submission.status == Status.PendingRemoval) {
                                        submission.registered = false;
                                        requester = request.requester;
                                    } else
                                        revert("Incorrect status.");
                            
                                    submission.status = Status.None;
                                    request.resolved = true;
                            
                                    if (request.vouches.length != 0)
                                        processVouches(_submissionID, requestID, AUTO_PROCESSED_VOUCH);
                            
                                    withdrawFeesAndRewards(requester, _submissionID, requestID, 0, 0); // Automatically withdraw for the requester.
                                }
                            
                                /** @dev Processes vouches of the resolved request, so vouchings of users who vouched for it can be used in other submissions.
                                 *  Penalizes users who vouched for bad submissions.
                                 *  @param _submissionID The address of the submission which vouches to iterate.
                                 *  @param _requestID The ID of the request which vouches to iterate.
                                 *  @param _iterations The number of iterations to go through.
                                 */
                                function processVouches(address _submissionID, uint _requestID, uint _iterations) public {
                                    Submission storage submission = submissions[_submissionID];
                                    Request storage request = submission.requests[_requestID];
                                    require(request.resolved, "Submission must be resolved");
                            
                                    uint lastProcessedVouch = request.lastProcessedVouch;
                                    uint endIndex = _iterations.addCap(lastProcessedVouch);
                                    uint vouchCount = request.vouches.length;
                            
                                    if (endIndex > vouchCount)
                                        endIndex = vouchCount;
                            
                                    Reason currentReason = request.currentReason;
                                    // If the ultimate challenger is defined that means that the request was ruled in favor of the challenger.
                                    bool applyPenalty = request.ultimateChallenger != address(0x0) && (currentReason == Reason.Duplicate || currentReason == Reason.DoesNotExist);
                                    for (uint i = lastProcessedVouch; i < endIndex; i++) {
                                        Submission storage voucher = submissions[request.vouches[i]];
                                        voucher.hasVouched = false;
                                        if (applyPenalty) {
                                            // Check the situation when vouching address is in the middle of reapplication process.
                                            if (voucher.status == Status.Vouching || voucher.status == Status.PendingRegistration)
                                                voucher.requests[voucher.requests.length - 1].requesterLost = true;
                            
                                            voucher.registered = false;
                                        }
                                    }
                                    request.lastProcessedVouch = uint32(endIndex);
                                }
                            
                                /** @dev Reimburses contributions if no disputes were raised. If a dispute was raised, sends the fee stake rewards and reimbursements proportionally to the contributions made to the winner of a dispute.
                                 *  @param _beneficiary The address that made contributions to a request.
                                 *  @param _submissionID The address of the submission with the request from which to withdraw.
                                 *  @param _requestID The request from which to withdraw.
                                 *  @param _challengeID The ID of the challenge from which to withdraw.
                                 *  @param _round The round from which to withdraw.
                                 */
                                function withdrawFeesAndRewards(address payable _beneficiary, address _submissionID, uint _requestID, uint _challengeID, uint _round) public {
                                    Submission storage submission = submissions[_submissionID];
                                    Request storage request = submission.requests[_requestID];
                                    Challenge storage challenge = request.challenges[_challengeID];
                                    Round storage round = challenge.rounds[_round];
                                    require(request.resolved, "Submission must be resolved");
                                    require(_beneficiary != address(0x0), "Beneficiary must not be empty");
                            
                                    Party ruling = challenge.ruling;
                                    uint reward;
                                    // Reimburse the payment if the last round wasn't fully funded.
                                    // Note that the 0 round is always considered funded if there is a challenge. If there was no challenge the requester will be reimbursed with the subsequent condition, since the ruling will be Party.None.
                                    if (_round != 0 && _round == challenge.lastRoundID) {
                                        reward = round.contributions[_beneficiary][uint(Party.Requester)] + round.contributions[_beneficiary][uint(Party.Challenger)];
                                    } else if (ruling == Party.None) {
                                        uint totalFeesInRound = round.paidFees[uint(Party.Challenger)] + round.paidFees[uint(Party.Requester)];
                                        uint claimableFees = round.contributions[_beneficiary][uint(Party.Challenger)] + round.contributions[_beneficiary][uint(Party.Requester)];
                                        reward = totalFeesInRound > 0 ? claimableFees * round.feeRewards / totalFeesInRound : 0;
                                    } else {
                                        // Challenger, who ultimately wins, will be able to get the deposit of the requester, even if he didn't participate in the initial dispute.
                                        if (_round == 0 && _beneficiary == request.ultimateChallenger && _challengeID == 0) {
                                            reward = round.feeRewards;
                                            round.feeRewards = 0;
                                        // This condition will prevent claiming a reward, intended for the ultimate challenger.
                                        } else if (request.ultimateChallenger==address(0x0) || _challengeID!=0 || _round!=0) {
                                            uint paidFees = round.paidFees[uint(ruling)];
                                            reward = paidFees > 0
                                                ? (round.contributions[_beneficiary][uint(ruling)] * round.feeRewards) / paidFees
                                                : 0;
                                        }
                                    }
                                    round.contributions[_beneficiary][uint(Party.Requester)] = 0;
                                    round.contributions[_beneficiary][uint(Party.Challenger)] = 0;
                                    _beneficiary.send(reward);
                                }
                            
                                /** @dev Give a ruling for a dispute. Can only be called by the arbitrator. TRUSTED.
                                 *  Accounts for the situation where the winner loses a case due to paying less appeal fees than expected.
                                 *  @param _disputeID ID of the dispute in the arbitrator contract.
                                 *  @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Refused to arbitrate".
                                 */
                                function rule(uint _disputeID, uint _ruling) public {
                                    Party resultRuling = Party(_ruling);
                                    DisputeData storage disputeData = arbitratorDisputeIDToDisputeData[msg.sender][_disputeID];
                                    address submissionID = disputeData.submissionID;
                                    uint challengeID = disputeData.challengeID;
                                    Submission storage submission = submissions[submissionID];
                            
                                    Request storage request = submission.requests[submission.requests.length - 1];
                                    Challenge storage challenge = request.challenges[challengeID];
                                    Round storage round = challenge.rounds[challenge.lastRoundID];
                                    ArbitratorData storage arbitratorData = arbitratorDataList[request.arbitratorDataID];
                            
                                    require(address(arbitratorData.arbitrator) == msg.sender);
                                    require(!request.resolved);
                            
                                    // The ruling is inverted if the loser paid its fees.
                                    if (round.sideFunded == Party.Requester) // If one side paid its fees, the ruling is in its favor. Note that if the other side had also paid, an appeal would have been created.
                                        resultRuling = Party.Requester;
                                    else if (round.sideFunded == Party.Challenger)
                                        resultRuling = Party.Challenger;
                            
                                    emit Ruling(IArbitrator(msg.sender), _disputeID, uint(resultRuling));
                                    executeRuling(submissionID, challengeID, resultRuling);
                                }
                            
                                /** @dev Submit a reference to evidence. EVENT.
                                 *  @param _submissionID The address of the submission which the evidence is related to.
                                 *  @param _evidence A link to an evidence using its URI.
                                 */
                                function submitEvidence(address _submissionID, string calldata _evidence) external {
                                    Submission storage submission = submissions[_submissionID];
                                    Request storage request = submission.requests[submission.requests.length - 1];
                                    ArbitratorData storage arbitratorData = arbitratorDataList[request.arbitratorDataID];
                            
                                    emit Evidence(arbitratorData.arbitrator, submission.requests.length - 1 + uint(_submissionID), msg.sender, _evidence);
                                }
                            
                                /* Internal */
                            
                                /** @dev Make a request to register/reapply the submission. Paying the full deposit right away is not required as it can be crowdfunded later.
                                 *  @param _submissionID The address of the submission.
                                 *  @param _evidence A link to evidence using its URI.
                                 */
                                function requestRegistration(address _submissionID, string memory _evidence) internal {
                                    Submission storage submission = submissions[_submissionID];
                                    Request storage request = submission.requests[submission.requests.length++];
                            
                                    uint arbitratorDataID = arbitratorDataList.length - 1;
                                    request.arbitratorDataID = uint16(arbitratorDataID);
                            
                                    Round storage round = request.challenges[0].rounds[0];
                            
                                    IArbitrator requestArbitrator = arbitratorDataList[arbitratorDataID].arbitrator;
                                    uint arbitrationCost = requestArbitrator.arbitrationCost(arbitratorDataList[arbitratorDataID].arbitratorExtraData);
                                    uint totalCost = arbitrationCost.addCap(submissionBaseDeposit);
                                    contribute(round, Party.Requester, msg.sender, msg.value, totalCost);
                            
                                    if (round.paidFees[uint(Party.Requester)] >= totalCost)
                                        round.sideFunded = Party.Requester;
                            
                                    if (bytes(_evidence).length > 0)
                                        emit Evidence(requestArbitrator, submission.requests.length - 1 + uint(_submissionID), msg.sender, _evidence);
                                }
                            
                                /** @dev Returns the contribution value and remainder from available ETH and required amount.
                                 *  @param _available The amount of ETH available for the contribution.
                                 *  @param _requiredAmount The amount of ETH required for the contribution.
                                 *  @return taken The amount of ETH taken.
                                 *  @return remainder The amount of ETH left from the contribution.
                                 */
                                function calculateContribution(uint _available, uint _requiredAmount)
                                    internal
                                    pure
                                    returns(uint taken, uint remainder)
                                {
                                    if (_requiredAmount > _available)
                                        return (_available, 0);
                            
                                    remainder = _available - _requiredAmount;
                                    return (_requiredAmount, remainder);
                                }
                            
                                /** @dev Make a fee contribution.
                                 *  @param _round The round to contribute to.
                                 *  @param _side The side to contribute to.
                                 *  @param _contributor The contributor.
                                 *  @param _amount The amount contributed.
                                 *  @param _totalRequired The total amount required for this side.
                                 *  @return The amount of fees contributed.
                                 */
                                function contribute(Round storage _round, Party _side, address payable _contributor, uint _amount, uint _totalRequired) internal returns (uint) {
                                    uint contribution;
                                    uint remainingETH;
                                    (contribution, remainingETH) = calculateContribution(_amount, _totalRequired.subCap(_round.paidFees[uint(_side)]));
                                    _round.contributions[_contributor][uint(_side)] += contribution;
                                    _round.paidFees[uint(_side)] += contribution;
                                    _round.feeRewards += contribution;
                            
                                    if (remainingETH != 0)
                                        _contributor.send(remainingETH);
                            
                                    return contribution;
                                }
                            
                                /** @dev Execute the ruling of a dispute.
                                 *  @param _submissionID ID of the submission.
                                 *  @param _challengeID ID of the challenge, related to the dispute.
                                 *  @param _winner Ruling given by the arbitrator. Note that 0 is reserved for "Refused to arbitrate".
                                 */
                                function executeRuling(address _submissionID, uint _challengeID, Party _winner) internal {
                                    Submission storage submission = submissions[_submissionID];
                                    uint requestID = submission.requests.length - 1;
                                    Status status = submission.status;
                            
                                    Request storage request = submission.requests[requestID];
                                    uint nbParallelDisputes = request.nbParallelDisputes;
                            
                                    Challenge storage challenge = request.challenges[_challengeID];
                            
                                    if (status == Status.PendingRemoval) {
                                        if (_winner == Party.Requester)
                                            submission.registered = false;
                            
                                        submission.status = Status.None;
                                        request.resolved = true;
                                    } else if (status == Status.PendingRegistration) {
                                        // For a registration request there can be more than one dispute.
                                        if (_winner == Party.Requester) {
                                            if (nbParallelDisputes == 1) {
                                                // Check whether or not the requester won all of his previous disputes for current reason.
                                                if (!request.requesterLost) {
                                                    if (request.usedReasons == FULL_REASONS_SET) {
                                                        // All reasons being used means the request can't be challenged again, so we can update its status.
                                                        submission.status = Status.None;
                                                        submission.registered = true;
                                                        submission.submissionTime = uint64(now);
                                                        request.resolved = true;
                                                    } else {
                                                        // Refresh the state of the request so it can be challenged again.
                                                        request.disputed = false;
                                                        request.challengePeriodStart = uint64(now);
                                                        request.currentReason = Reason.None;
                                                    }
                                                } else {
                                                    submission.status = Status.None;
                                                    request.resolved = true;
                                                }
                                            }
                                        // Challenger won or it’s a tie.
                                        } else {
                                            request.requesterLost = true;
                                            // Update the status of the submission if there is no more disputes left.
                                            if (nbParallelDisputes == 1) {
                                                submission.status = Status.None;
                                                request.resolved = true;
                                            }
                                            // Store the challenger that made the requester lose. Update the challenger if there is a duplicate with lower submission time, which is indicated by submission's index.
                                            if (_winner==Party.Challenger && (request.ultimateChallenger==address(0x0) || challenge.duplicateSubmissionIndex<request.currentDuplicateIndex)) {
                                                request.ultimateChallenger = challenge.challenger;
                                                request.currentDuplicateIndex = challenge.duplicateSubmissionIndex;
                                            }
                                        }
                                    }
                                    // Decrease the number of parallel disputes each time the dispute is resolved. Store the rulings of each dispute for correct distribution of rewards.
                                    request.nbParallelDisputes--;
                                    challenge.ruling = _winner;
                                    emit ChallengeResolved(_submissionID, requestID, _challengeID);
                                }
                            
                                // ************************ //
                                // *       Getters        * //
                                // ************************ //
                            
                                /** @dev Returns true if the submission is registered and not expired.
                                 *  @param _submissionID The address of the submission.
                                 *  @return Whether the submission is registered or not.
                                 */
                                function isRegistered(address _submissionID) external view returns (bool) {
                                    Submission storage submission = submissions[_submissionID];
                                    return submission.registered && now - submission.submissionTime <= submissionDuration;
                                }
                            
                                /** @dev Gets the number of times the arbitrator data was updated.
                                 *  @return The number of arbitrator data updates.
                                 */
                                function getArbitratorDataListCount() external view returns (uint) {
                                    return arbitratorDataList.length;
                                }
                            
                                /** @dev Checks whether the duplicate address has been used in challenging the request or not.
                                 *  @param _submissionID The address of the submission to check.
                                 *  @param _requestID The request to check.
                                 *  @param _duplicateID The duplicate to check.
                                 *  @return Whether the duplicate has been used.
                                 */
                                function checkRequestDuplicates(address _submissionID, uint _requestID, address _duplicateID) external view returns (bool) {
                                    Request storage request = submissions[_submissionID].requests[_requestID];
                                    return request.challengeDuplicates[_duplicateID];
                                }
                            
                                /** @dev Gets the contributions made by a party for a given round of a given challenge of a request.
                                 *  @param _submissionID The address of the submission.
                                 *  @param _requestID The request to query.
                                 *  @param _challengeID the challenge to query.
                                 *  @param _round The round to query.
                                 *  @param _contributor The address of the contributor.
                                 *  @return The contributions.
                                 */
                                function getContributions(
                                    address _submissionID,
                                    uint _requestID,
                                    uint _challengeID,
                                    uint _round,
                                    address _contributor
                                ) external view returns(uint[3] memory contributions) {
                                    Request storage request = submissions[_submissionID].requests[_requestID];
                                    Challenge storage challenge = request.challenges[_challengeID];
                                    Round storage round = challenge.rounds[_round];
                                    contributions = round.contributions[_contributor];
                                }
                            
                                /** @dev Returns the information of the submission. Includes length of requests array.
                                 *  @param _submissionID The address of the queried submission.
                                 *  @return The information of the submission.
                                 */
                                function getSubmissionInfo(address _submissionID)
                                    external
                                    view
                                    returns (
                                        Status status,
                                        uint64 submissionTime,
                                        uint64 index,
                                        bool registered,
                                        bool hasVouched,
                                        uint numberOfRequests
                                    )
                                {
                                    Submission storage submission = submissions[_submissionID];
                                    return (
                                        submission.status,
                                        submission.submissionTime,
                                        submission.index,
                                        submission.registered,
                                        submission.hasVouched,
                                        submission.requests.length
                                    );
                                }
                            
                                /** @dev Gets the information of a particular challenge of the request.
                                 *  @param _submissionID The address of the queried submission.
                                 *  @param _requestID The request to query.
                                 *  @param _challengeID The challenge to query.
                                 *  @return The information of the challenge.
                                 */
                                function getChallengeInfo(address _submissionID, uint _requestID, uint _challengeID)
                                    external
                                    view
                                    returns (
                                        uint16 lastRoundID,
                                        address challenger,
                                        uint disputeID,
                                        Party ruling,
                                        uint64 duplicateSubmissionIndex
                                    )
                                {
                                    Request storage request = submissions[_submissionID].requests[_requestID];
                                    Challenge storage challenge = request.challenges[_challengeID];
                                    return (
                                        challenge.lastRoundID,
                                        challenge.challenger,
                                        challenge.disputeID,
                                        challenge.ruling,
                                        challenge.duplicateSubmissionIndex
                                    );
                                }
                            
                                /** @dev Gets information of a request of a submission.
                                 *  @param _submissionID The address of the queried submission.
                                 *  @param _requestID The request to be queried.
                                 *  @return The request information.
                                 */
                                function getRequestInfo(address _submissionID, uint _requestID)
                                    external
                                    view
                                    returns (
                                        bool disputed,
                                        bool resolved,
                                        bool requesterLost,
                                        Reason currentReason,
                                        uint16 nbParallelDisputes,
                                        uint16 lastChallengeID,
                                        uint16 arbitratorDataID,
                                        address payable requester,
                                        address payable ultimateChallenger,
                                        uint8 usedReasons
                                    )
                                {
                                    Request storage request = submissions[_submissionID].requests[_requestID];
                                    return (
                                        request.disputed,
                                        request.resolved,
                                        request.requesterLost,
                                        request.currentReason,
                                        request.nbParallelDisputes,
                                        request.lastChallengeID,
                                        request.arbitratorDataID,
                                        request.requester,
                                        request.ultimateChallenger,
                                        request.usedReasons
                                    );
                                }
                            
                                /** @dev Gets the number of vouches of a particular request.
                                 *  @param _submissionID The address of the queried submission.
                                 *  @param _requestID The request to query.
                                 *  @return The current number of vouches.
                                 */
                                function getNumberOfVouches(address _submissionID, uint _requestID) external view returns (uint) {
                                    Request storage request = submissions[_submissionID].requests[_requestID];
                                    return request.vouches.length;
                                }
                            
                                /** @dev Gets the information of a round of a request.
                                 *  @param _submissionID The address of the queried submission.
                                 *  @param _requestID The request to query.
                                 *  @param _challengeID The challenge to query.
                                 *  @param _round The round to query.
                                 *  @return The round information.
                                 */
                                function getRoundInfo(address _submissionID, uint _requestID, uint _challengeID, uint _round)
                                    external
                                    view
                                    returns (
                                        bool appealed,
                                        uint[3] memory paidFees,
                                        Party sideFunded,
                                        uint feeRewards
                                    )
                                {
                                    Request storage request = submissions[_submissionID].requests[_requestID];
                                    Challenge storage challenge = request.challenges[_challengeID];
                                    Round storage round = challenge.rounds[_round];
                                    appealed = _round < (challenge.lastRoundID);
                                    return (
                                        appealed,
                                        round.paidFees,
                                        round.sideFunded,
                                        round.feeRewards
                                    );
                                }
                            }

                            File 10 of 10: FiatTokenV2_1
                            // File: @openzeppelin/contracts/math/SafeMath.sol
                            
                            // SPDX-License-Identifier: MIT
                            
                            pragma solidity ^0.6.0;
                            
                            /**
                             * @dev Wrappers over Solidity's arithmetic operations with added overflow
                             * checks.
                             *
                             * Arithmetic operations in Solidity wrap on overflow. This can easily result
                             * in bugs, because programmers usually assume that an overflow raises an
                             * error, which is the standard behavior in high level programming languages.
                             * `SafeMath` restores this intuition by reverting the transaction when 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.
                             */
                            library SafeMath {
                                /**
                                 * @dev Returns the addition of two unsigned integers, reverting on
                                 * overflow.
                                 *
                                 * Counterpart to Solidity's `+` operator.
                                 *
                                 * Requirements:
                                 *
                                 * - Addition cannot overflow.
                                 */
                                function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                    uint256 c = a + b;
                                    require(c >= a, "SafeMath: addition overflow");
                            
                                    return c;
                                }
                            
                                /**
                                 * @dev Returns the subtraction of two unsigned integers, reverting on
                                 * overflow (when the result is negative).
                                 *
                                 * Counterpart to Solidity's `-` operator.
                                 *
                                 * Requirements:
                                 *
                                 * - Subtraction cannot overflow.
                                 */
                                function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                    return sub(a, b, "SafeMath: subtraction overflow");
                                }
                            
                                /**
                                 * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                 * overflow (when the result is negative).
                                 *
                                 * Counterpart to Solidity's `-` operator.
                                 *
                                 * Requirements:
                                 *
                                 * - Subtraction cannot overflow.
                                 */
                                function sub(
                                    uint256 a,
                                    uint256 b,
                                    string memory errorMessage
                                ) internal pure returns (uint256) {
                                    require(b <= a, errorMessage);
                                    uint256 c = a - b;
                            
                                    return c;
                                }
                            
                                /**
                                 * @dev Returns the multiplication of two unsigned integers, reverting on
                                 * overflow.
                                 *
                                 * Counterpart to Solidity's `*` operator.
                                 *
                                 * Requirements:
                                 *
                                 * - Multiplication cannot overflow.
                                 */
                                function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                    // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                                    // benefit is lost if 'b' is also tested.
                                    // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                                    if (a == 0) {
                                        return 0;
                                    }
                            
                                    uint256 c = a * b;
                                    require(c / a == b, "SafeMath: multiplication overflow");
                            
                                    return c;
                                }
                            
                                /**
                                 * @dev Returns the integer division of two unsigned integers. Reverts on
                                 * division by zero. The result is rounded towards zero.
                                 *
                                 * Counterpart to Solidity's `/` operator. Note: this function uses a
                                 * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                 * uses an invalid opcode to revert (consuming all remaining gas).
                                 *
                                 * Requirements:
                                 *
                                 * - The divisor cannot be zero.
                                 */
                                function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                    return div(a, b, "SafeMath: division by zero");
                                }
                            
                                /**
                                 * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
                                 * division by zero. The result is rounded towards zero.
                                 *
                                 * Counterpart to Solidity's `/` operator. Note: this function uses a
                                 * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                 * uses an invalid opcode to revert (consuming all remaining gas).
                                 *
                                 * Requirements:
                                 *
                                 * - The divisor cannot be zero.
                                 */
                                function div(
                                    uint256 a,
                                    uint256 b,
                                    string memory errorMessage
                                ) internal pure returns (uint256) {
                                    require(b > 0, errorMessage);
                                    uint256 c = a / b;
                                    // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                            
                                    return c;
                                }
                            
                                /**
                                 * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                 * Reverts when dividing by zero.
                                 *
                                 * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                 * opcode (which leaves remaining gas untouched) while Solidity uses an
                                 * invalid opcode to revert (consuming all remaining gas).
                                 *
                                 * Requirements:
                                 *
                                 * - The divisor cannot be zero.
                                 */
                                function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                    return mod(a, b, "SafeMath: modulo by zero");
                                }
                            
                                /**
                                 * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                 * Reverts with custom message when dividing by zero.
                                 *
                                 * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                 * opcode (which leaves remaining gas untouched) while Solidity uses an
                                 * invalid opcode to revert (consuming all remaining gas).
                                 *
                                 * Requirements:
                                 *
                                 * - The divisor cannot be zero.
                                 */
                                function mod(
                                    uint256 a,
                                    uint256 b,
                                    string memory errorMessage
                                ) internal pure returns (uint256) {
                                    require(b != 0, errorMessage);
                                    return a % b;
                                }
                            }
                            
                            // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
                            
                            pragma solidity ^0.6.0;
                            
                            /**
                             * @dev Interface of the ERC20 standard as defined in the EIP.
                             */
                            interface IERC20 {
                                /**
                                 * @dev Returns the amount of tokens in existence.
                                 */
                                function totalSupply() external view returns (uint256);
                            
                                /**
                                 * @dev Returns the amount of tokens owned by `account`.
                                 */
                                function balanceOf(address account) external view returns (uint256);
                            
                                /**
                                 * @dev Moves `amount` tokens from the caller's account to `recipient`.
                                 *
                                 * Returns a boolean value indicating whether the operation succeeded.
                                 *
                                 * Emits a {Transfer} event.
                                 */
                                function transfer(address recipient, 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 `sender` to `recipient` 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 sender,
                                    address recipient,
                                    uint256 amount
                                ) external returns (bool);
                            
                                /**
                                 * @dev Emitted when `value` tokens are moved from one account (`from`) to
                                 * another (`to`).
                                 *
                                 * Note that `value` may be zero.
                                 */
                                event Transfer(address indexed from, address indexed to, uint256 value);
                            
                                /**
                                 * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                                 * a call to {approve}. `value` is the new allowance.
                                 */
                                event Approval(
                                    address indexed owner,
                                    address indexed spender,
                                    uint256 value
                                );
                            }
                            
                            // File: contracts/v1/AbstractFiatTokenV1.sol
                            
                            /**
                             * Copyright (c) 2018-2020 CENTRE SECZ
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            
                            pragma solidity 0.6.12;
                            
                            abstract contract AbstractFiatTokenV1 is IERC20 {
                                function _approve(
                                    address owner,
                                    address spender,
                                    uint256 value
                                ) internal virtual;
                            
                                function _transfer(
                                    address from,
                                    address to,
                                    uint256 value
                                ) internal virtual;
                            }
                            
                            // File: contracts/v1/Ownable.sol
                            
                            /**
                             * Copyright (c) 2018 zOS Global Limited.
                             * Copyright (c) 2018-2020 CENTRE SECZ
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            pragma solidity 0.6.12;
                            
                            /**
                             * @notice The Ownable contract has an owner address, and provides basic
                             * authorization control functions
                             * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol
                             * Modifications:
                             * 1. Consolidate OwnableStorage into this contract (7/13/18)
                             * 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20)
                             * 3. Make public functions external (5/27/20)
                             */
                            contract Ownable {
                                // Owner of the contract
                                address private _owner;
                            
                                /**
                                 * @dev Event to show ownership has been transferred
                                 * @param previousOwner representing the address of the previous owner
                                 * @param newOwner representing the address of the new owner
                                 */
                                event OwnershipTransferred(address previousOwner, address newOwner);
                            
                                /**
                                 * @dev The constructor sets the original owner of the contract to the sender account.
                                 */
                                constructor() public {
                                    setOwner(msg.sender);
                                }
                            
                                /**
                                 * @dev Tells the address of the owner
                                 * @return the address of the owner
                                 */
                                function owner() external view returns (address) {
                                    return _owner;
                                }
                            
                                /**
                                 * @dev Sets a new owner address
                                 */
                                function setOwner(address newOwner) internal {
                                    _owner = newOwner;
                                }
                            
                                /**
                                 * @dev Throws if called by any account other than the owner.
                                 */
                                modifier onlyOwner() {
                                    require(msg.sender == _owner, "Ownable: caller is not the owner");
                                    _;
                                }
                            
                                /**
                                 * @dev Allows the current owner to transfer control of the contract to a newOwner.
                                 * @param newOwner The address to transfer ownership to.
                                 */
                                function transferOwnership(address newOwner) external onlyOwner {
                                    require(
                                        newOwner != address(0),
                                        "Ownable: new owner is the zero address"
                                    );
                                    emit OwnershipTransferred(_owner, newOwner);
                                    setOwner(newOwner);
                                }
                            }
                            
                            // File: contracts/v1/Pausable.sol
                            
                            /**
                             * Copyright (c) 2016 Smart Contract Solutions, Inc.
                             * Copyright (c) 2018-2020 CENTRE SECZ0
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            
                            pragma solidity 0.6.12;
                            
                            /**
                             * @notice Base contract which allows children to implement an emergency stop
                             * mechanism
                             * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol
                             * Modifications:
                             * 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018)
                             * 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018)
                             * 3. Removed whenPaused (6/14/2018)
                             * 4. Switches ownable library to use ZeppelinOS (7/12/18)
                             * 5. Remove constructor (7/13/18)
                             * 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20)
                             * 7. Make public functions external (5/27/20)
                             */
                            contract Pausable is Ownable {
                                event Pause();
                                event Unpause();
                                event PauserChanged(address indexed newAddress);
                            
                                address public pauser;
                                bool public paused = false;
                            
                                /**
                                 * @dev Modifier to make a function callable only when the contract is not paused.
                                 */
                                modifier whenNotPaused() {
                                    require(!paused, "Pausable: paused");
                                    _;
                                }
                            
                                /**
                                 * @dev throws if called by any account other than the pauser
                                 */
                                modifier onlyPauser() {
                                    require(msg.sender == pauser, "Pausable: caller is not the pauser");
                                    _;
                                }
                            
                                /**
                                 * @dev called by the owner to pause, triggers stopped state
                                 */
                                function pause() external onlyPauser {
                                    paused = true;
                                    emit Pause();
                                }
                            
                                /**
                                 * @dev called by the owner to unpause, returns to normal state
                                 */
                                function unpause() external onlyPauser {
                                    paused = false;
                                    emit Unpause();
                                }
                            
                                /**
                                 * @dev update the pauser role
                                 */
                                function updatePauser(address _newPauser) external onlyOwner {
                                    require(
                                        _newPauser != address(0),
                                        "Pausable: new pauser is the zero address"
                                    );
                                    pauser = _newPauser;
                                    emit PauserChanged(pauser);
                                }
                            }
                            
                            // File: contracts/v1/Blacklistable.sol
                            
                            /**
                             * Copyright (c) 2018-2020 CENTRE SECZ
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            
                            pragma solidity 0.6.12;
                            
                            /**
                             * @title Blacklistable Token
                             * @dev Allows accounts to be blacklisted by a "blacklister" role
                             */
                            contract Blacklistable is Ownable {
                                address public blacklister;
                                mapping(address => bool) internal blacklisted;
                            
                                event Blacklisted(address indexed _account);
                                event UnBlacklisted(address indexed _account);
                                event BlacklisterChanged(address indexed newBlacklister);
                            
                                /**
                                 * @dev Throws if called by any account other than the blacklister
                                 */
                                modifier onlyBlacklister() {
                                    require(
                                        msg.sender == blacklister,
                                        "Blacklistable: caller is not the blacklister"
                                    );
                                    _;
                                }
                            
                                /**
                                 * @dev Throws if argument account is blacklisted
                                 * @param _account The address to check
                                 */
                                modifier notBlacklisted(address _account) {
                                    require(
                                        !blacklisted[_account],
                                        "Blacklistable: account is blacklisted"
                                    );
                                    _;
                                }
                            
                                /**
                                 * @dev Checks if account is blacklisted
                                 * @param _account The address to check
                                 */
                                function isBlacklisted(address _account) external view returns (bool) {
                                    return blacklisted[_account];
                                }
                            
                                /**
                                 * @dev Adds account to blacklist
                                 * @param _account The address to blacklist
                                 */
                                function blacklist(address _account) external onlyBlacklister {
                                    blacklisted[_account] = true;
                                    emit Blacklisted(_account);
                                }
                            
                                /**
                                 * @dev Removes account from blacklist
                                 * @param _account The address to remove from the blacklist
                                 */
                                function unBlacklist(address _account) external onlyBlacklister {
                                    blacklisted[_account] = false;
                                    emit UnBlacklisted(_account);
                                }
                            
                                function updateBlacklister(address _newBlacklister) external onlyOwner {
                                    require(
                                        _newBlacklister != address(0),
                                        "Blacklistable: new blacklister is the zero address"
                                    );
                                    blacklister = _newBlacklister;
                                    emit BlacklisterChanged(blacklister);
                                }
                            }
                            
                            // File: contracts/v1/FiatTokenV1.sol
                            
                            /**
                             *
                             * Copyright (c) 2018-2020 CENTRE SECZ
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            
                            pragma solidity 0.6.12;
                            
                            /**
                             * @title FiatToken
                             * @dev ERC20 Token backed by fiat reserves
                             */
                            contract FiatTokenV1 is AbstractFiatTokenV1, Ownable, Pausable, Blacklistable {
                                using SafeMath for uint256;
                            
                                string public name;
                                string public symbol;
                                uint8 public decimals;
                                string public currency;
                                address public masterMinter;
                                bool internal initialized;
                            
                                mapping(address => uint256) internal balances;
                                mapping(address => mapping(address => uint256)) internal allowed;
                                uint256 internal totalSupply_ = 0;
                                mapping(address => bool) internal minters;
                                mapping(address => uint256) internal minterAllowed;
                            
                                event Mint(address indexed minter, address indexed to, uint256 amount);
                                event Burn(address indexed burner, uint256 amount);
                                event MinterConfigured(address indexed minter, uint256 minterAllowedAmount);
                                event MinterRemoved(address indexed oldMinter);
                                event MasterMinterChanged(address indexed newMasterMinter);
                            
                                function initialize(
                                    string memory tokenName,
                                    string memory tokenSymbol,
                                    string memory tokenCurrency,
                                    uint8 tokenDecimals,
                                    address newMasterMinter,
                                    address newPauser,
                                    address newBlacklister,
                                    address newOwner
                                ) public {
                                    require(!initialized, "FiatToken: contract is already initialized");
                                    require(
                                        newMasterMinter != address(0),
                                        "FiatToken: new masterMinter is the zero address"
                                    );
                                    require(
                                        newPauser != address(0),
                                        "FiatToken: new pauser is the zero address"
                                    );
                                    require(
                                        newBlacklister != address(0),
                                        "FiatToken: new blacklister is the zero address"
                                    );
                                    require(
                                        newOwner != address(0),
                                        "FiatToken: new owner is the zero address"
                                    );
                            
                                    name = tokenName;
                                    symbol = tokenSymbol;
                                    currency = tokenCurrency;
                                    decimals = tokenDecimals;
                                    masterMinter = newMasterMinter;
                                    pauser = newPauser;
                                    blacklister = newBlacklister;
                                    setOwner(newOwner);
                                    initialized = true;
                                }
                            
                                /**
                                 * @dev Throws if called by any account other than a minter
                                 */
                                modifier onlyMinters() {
                                    require(minters[msg.sender], "FiatToken: caller is not a minter");
                                    _;
                                }
                            
                                /**
                                 * @dev Function to mint tokens
                                 * @param _to The address that will receive the minted tokens.
                                 * @param _amount The amount of tokens to mint. Must be less than or equal
                                 * to the minterAllowance of the caller.
                                 * @return A boolean that indicates if the operation was successful.
                                 */
                                function mint(address _to, uint256 _amount)
                                    external
                                    whenNotPaused
                                    onlyMinters
                                    notBlacklisted(msg.sender)
                                    notBlacklisted(_to)
                                    returns (bool)
                                {
                                    require(_to != address(0), "FiatToken: mint to the zero address");
                                    require(_amount > 0, "FiatToken: mint amount not greater than 0");
                            
                                    uint256 mintingAllowedAmount = minterAllowed[msg.sender];
                                    require(
                                        _amount <= mintingAllowedAmount,
                                        "FiatToken: mint amount exceeds minterAllowance"
                                    );
                            
                                    totalSupply_ = totalSupply_.add(_amount);
                                    balances[_to] = balances[_to].add(_amount);
                                    minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount);
                                    emit Mint(msg.sender, _to, _amount);
                                    emit Transfer(address(0), _to, _amount);
                                    return true;
                                }
                            
                                /**
                                 * @dev Throws if called by any account other than the masterMinter
                                 */
                                modifier onlyMasterMinter() {
                                    require(
                                        msg.sender == masterMinter,
                                        "FiatToken: caller is not the masterMinter"
                                    );
                                    _;
                                }
                            
                                /**
                                 * @dev Get minter allowance for an account
                                 * @param minter The address of the minter
                                 */
                                function minterAllowance(address minter) external view returns (uint256) {
                                    return minterAllowed[minter];
                                }
                            
                                /**
                                 * @dev Checks if account is a minter
                                 * @param account The address to check
                                 */
                                function isMinter(address account) external view returns (bool) {
                                    return minters[account];
                                }
                            
                                /**
                                 * @notice Amount of remaining tokens spender is allowed to transfer on
                                 * behalf of the token owner
                                 * @param owner     Token owner's address
                                 * @param spender   Spender's address
                                 * @return Allowance amount
                                 */
                                function allowance(address owner, address spender)
                                    external
                                    override
                                    view
                                    returns (uint256)
                                {
                                    return allowed[owner][spender];
                                }
                            
                                /**
                                 * @dev Get totalSupply of token
                                 */
                                function totalSupply() external override view returns (uint256) {
                                    return totalSupply_;
                                }
                            
                                /**
                                 * @dev Get token balance of an account
                                 * @param account address The account
                                 */
                                function balanceOf(address account)
                                    external
                                    override
                                    view
                                    returns (uint256)
                                {
                                    return balances[account];
                                }
                            
                                /**
                                 * @notice Set spender's allowance over the caller's tokens to be a given
                                 * value.
                                 * @param spender   Spender's address
                                 * @param value     Allowance amount
                                 * @return True if successful
                                 */
                                function approve(address spender, uint256 value)
                                    external
                                    override
                                    whenNotPaused
                                    notBlacklisted(msg.sender)
                                    notBlacklisted(spender)
                                    returns (bool)
                                {
                                    _approve(msg.sender, spender, value);
                                    return true;
                                }
                            
                                /**
                                 * @dev Internal function to set allowance
                                 * @param owner     Token owner's address
                                 * @param spender   Spender's address
                                 * @param value     Allowance amount
                                 */
                                function _approve(
                                    address owner,
                                    address spender,
                                    uint256 value
                                ) internal override {
                                    require(owner != address(0), "ERC20: approve from the zero address");
                                    require(spender != address(0), "ERC20: approve to the zero address");
                                    allowed[owner][spender] = value;
                                    emit Approval(owner, spender, value);
                                }
                            
                                /**
                                 * @notice Transfer tokens by spending allowance
                                 * @param from  Payer's address
                                 * @param to    Payee's address
                                 * @param value Transfer amount
                                 * @return True if successful
                                 */
                                function transferFrom(
                                    address from,
                                    address to,
                                    uint256 value
                                )
                                    external
                                    override
                                    whenNotPaused
                                    notBlacklisted(msg.sender)
                                    notBlacklisted(from)
                                    notBlacklisted(to)
                                    returns (bool)
                                {
                                    require(
                                        value <= allowed[from][msg.sender],
                                        "ERC20: transfer amount exceeds allowance"
                                    );
                                    _transfer(from, to, value);
                                    allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
                                    return true;
                                }
                            
                                /**
                                 * @notice Transfer tokens from the caller
                                 * @param to    Payee's address
                                 * @param value Transfer amount
                                 * @return True if successful
                                 */
                                function transfer(address to, uint256 value)
                                    external
                                    override
                                    whenNotPaused
                                    notBlacklisted(msg.sender)
                                    notBlacklisted(to)
                                    returns (bool)
                                {
                                    _transfer(msg.sender, to, value);
                                    return true;
                                }
                            
                                /**
                                 * @notice Internal function to process transfers
                                 * @param from  Payer's address
                                 * @param to    Payee's address
                                 * @param value Transfer amount
                                 */
                                function _transfer(
                                    address from,
                                    address to,
                                    uint256 value
                                ) internal override {
                                    require(from != address(0), "ERC20: transfer from the zero address");
                                    require(to != address(0), "ERC20: transfer to the zero address");
                                    require(
                                        value <= balances[from],
                                        "ERC20: transfer amount exceeds balance"
                                    );
                            
                                    balances[from] = balances[from].sub(value);
                                    balances[to] = balances[to].add(value);
                                    emit Transfer(from, to, value);
                                }
                            
                                /**
                                 * @dev Function to add/update a new minter
                                 * @param minter The address of the minter
                                 * @param minterAllowedAmount The minting amount allowed for the minter
                                 * @return True if the operation was successful.
                                 */
                                function configureMinter(address minter, uint256 minterAllowedAmount)
                                    external
                                    whenNotPaused
                                    onlyMasterMinter
                                    returns (bool)
                                {
                                    minters[minter] = true;
                                    minterAllowed[minter] = minterAllowedAmount;
                                    emit MinterConfigured(minter, minterAllowedAmount);
                                    return true;
                                }
                            
                                /**
                                 * @dev Function to remove a minter
                                 * @param minter The address of the minter to remove
                                 * @return True if the operation was successful.
                                 */
                                function removeMinter(address minter)
                                    external
                                    onlyMasterMinter
                                    returns (bool)
                                {
                                    minters[minter] = false;
                                    minterAllowed[minter] = 0;
                                    emit MinterRemoved(minter);
                                    return true;
                                }
                            
                                /**
                                 * @dev allows a minter to burn some of its own tokens
                                 * Validates that caller is a minter and that sender is not blacklisted
                                 * amount is less than or equal to the minter's account balance
                                 * @param _amount uint256 the amount of tokens to be burned
                                 */
                                function burn(uint256 _amount)
                                    external
                                    whenNotPaused
                                    onlyMinters
                                    notBlacklisted(msg.sender)
                                {
                                    uint256 balance = balances[msg.sender];
                                    require(_amount > 0, "FiatToken: burn amount not greater than 0");
                                    require(balance >= _amount, "FiatToken: burn amount exceeds balance");
                            
                                    totalSupply_ = totalSupply_.sub(_amount);
                                    balances[msg.sender] = balance.sub(_amount);
                                    emit Burn(msg.sender, _amount);
                                    emit Transfer(msg.sender, address(0), _amount);
                                }
                            
                                function updateMasterMinter(address _newMasterMinter) external onlyOwner {
                                    require(
                                        _newMasterMinter != address(0),
                                        "FiatToken: new masterMinter is the zero address"
                                    );
                                    masterMinter = _newMasterMinter;
                                    emit MasterMinterChanged(masterMinter);
                                }
                            }
                            
                            // File: @openzeppelin/contracts/utils/Address.sol
                            
                            pragma solidity ^0.6.2;
                            
                            /**
                             * @dev Collection of functions related to the address type
                             */
                            library Address {
                                /**
                                 * @dev Returns true if `account` is a contract.
                                 *
                                 * [IMPORTANT]
                                 * ====
                                 * It is unsafe to assume that an address for which this function returns
                                 * false is an externally-owned account (EOA) and not a contract.
                                 *
                                 * Among others, `isContract` will return false for the following
                                 * types of addresses:
                                 *
                                 *  - an externally-owned account
                                 *  - a contract in construction
                                 *  - an address where a contract will be created
                                 *  - an address where a contract lived, but was destroyed
                                 * ====
                                 */
                                function isContract(address account) internal view returns (bool) {
                                    // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
                                    // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
                                    // for accounts without code, i.e. `keccak256('')`
                                    bytes32 codehash;
                            
                                        bytes32 accountHash
                                     = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        codehash := extcodehash(account)
                                    }
                                    return (codehash != accountHash && codehash != 0x0);
                                }
                            
                                /**
                                 * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                                 * `recipient`, forwarding all available gas and reverting on errors.
                                 *
                                 * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                                 * of certain opcodes, possibly making contracts go over the 2300 gas limit
                                 * imposed by `transfer`, making them unable to receive funds via
                                 * `transfer`. {sendValue} removes this limitation.
                                 *
                                 * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                                 *
                                 * IMPORTANT: because control is transferred to `recipient`, care must be
                                 * taken to not create reentrancy vulnerabilities. Consider using
                                 * {ReentrancyGuard} or the
                                 * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                                 */
                                function sendValue(address payable recipient, uint256 amount) internal {
                                    require(
                                        address(this).balance >= amount,
                                        "Address: insufficient balance"
                                    );
                            
                                    // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                                    (bool success, ) = recipient.call{ value: amount }("");
                                    require(
                                        success,
                                        "Address: unable to send value, recipient may have reverted"
                                    );
                                }
                            
                                /**
                                 * @dev Performs a Solidity function call using a low level `call`. A
                                 * plain`call` is an unsafe replacement for a function call: use this
                                 * function instead.
                                 *
                                 * If `target` reverts with a revert reason, it is bubbled up by this
                                 * function (like regular Solidity function calls).
                                 *
                                 * Returns the raw returned data. To convert to the expected return value,
                                 * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                                 *
                                 * Requirements:
                                 *
                                 * - `target` must be a contract.
                                 * - calling `target` with `data` must not revert.
                                 *
                                 * _Available since v3.1._
                                 */
                                function functionCall(address target, bytes memory data)
                                    internal
                                    returns (bytes memory)
                                {
                                    return functionCall(target, data, "Address: low-level call failed");
                                }
                            
                                /**
                                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                                 * `errorMessage` as a fallback revert reason when `target` reverts.
                                 *
                                 * _Available since v3.1._
                                 */
                                function functionCall(
                                    address target,
                                    bytes memory data,
                                    string memory errorMessage
                                ) internal returns (bytes memory) {
                                    return _functionCallWithValue(target, data, 0, errorMessage);
                                }
                            
                                /**
                                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                                 * but also transferring `value` wei to `target`.
                                 *
                                 * Requirements:
                                 *
                                 * - the calling contract must have an ETH balance of at least `value`.
                                 * - the called Solidity function must be `payable`.
                                 *
                                 * _Available since v3.1._
                                 */
                                function functionCallWithValue(
                                    address target,
                                    bytes memory data,
                                    uint256 value
                                ) internal returns (bytes memory) {
                                    return
                                        functionCallWithValue(
                                            target,
                                            data,
                                            value,
                                            "Address: low-level call with value failed"
                                        );
                                }
                            
                                /**
                                 * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                                 * with `errorMessage` as a fallback revert reason when `target` reverts.
                                 *
                                 * _Available since v3.1._
                                 */
                                function functionCallWithValue(
                                    address target,
                                    bytes memory data,
                                    uint256 value,
                                    string memory errorMessage
                                ) internal returns (bytes memory) {
                                    require(
                                        address(this).balance >= value,
                                        "Address: insufficient balance for call"
                                    );
                                    return _functionCallWithValue(target, data, value, errorMessage);
                                }
                            
                                function _functionCallWithValue(
                                    address target,
                                    bytes memory data,
                                    uint256 weiValue,
                                    string memory errorMessage
                                ) private returns (bytes memory) {
                                    require(isContract(target), "Address: call to non-contract");
                            
                                    // solhint-disable-next-line avoid-low-level-calls
                                    (bool success, bytes memory returndata) = target.call{
                                        value: weiValue
                                    }(data);
                                    if (success) {
                                        return returndata;
                                    } else {
                                        // Look for revert reason and bubble it up if present
                                        if (returndata.length > 0) {
                                            // The easiest way to bubble the revert reason is using memory via assembly
                            
                                            // solhint-disable-next-line no-inline-assembly
                                            assembly {
                                                let returndata_size := mload(returndata)
                                                revert(add(32, returndata), returndata_size)
                                            }
                                        } else {
                                            revert(errorMessage);
                                        }
                                    }
                                }
                            }
                            
                            // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
                            
                            pragma solidity ^0.6.0;
                            
                            /**
                             * @title SafeERC20
                             * @dev Wrappers around ERC20 operations that throw on failure (when the token
                             * contract returns false). Tokens that return no value (and instead revert or
                             * throw on failure) are also supported, non-reverting calls are assumed to be
                             * successful.
                             * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                             * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                             */
                            library SafeERC20 {
                                using SafeMath for uint256;
                                using Address for address;
                            
                                function safeTransfer(
                                    IERC20 token,
                                    address to,
                                    uint256 value
                                ) internal {
                                    _callOptionalReturn(
                                        token,
                                        abi.encodeWithSelector(token.transfer.selector, to, value)
                                    );
                                }
                            
                                function safeTransferFrom(
                                    IERC20 token,
                                    address from,
                                    address to,
                                    uint256 value
                                ) internal {
                                    _callOptionalReturn(
                                        token,
                                        abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
                                    );
                                }
                            
                                /**
                                 * @dev Deprecated. This function has issues similar to the ones found in
                                 * {IERC20-approve}, and its usage is discouraged.
                                 *
                                 * Whenever possible, use {safeIncreaseAllowance} and
                                 * {safeDecreaseAllowance} instead.
                                 */
                                function safeApprove(
                                    IERC20 token,
                                    address spender,
                                    uint256 value
                                ) internal {
                                    // safeApprove should only be called when setting an initial allowance,
                                    // or when resetting it to zero. To increase and decrease it, use
                                    // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                    // solhint-disable-next-line max-line-length
                                    require(
                                        (value == 0) || (token.allowance(address(this), spender) == 0),
                                        "SafeERC20: approve from non-zero to non-zero allowance"
                                    );
                                    _callOptionalReturn(
                                        token,
                                        abi.encodeWithSelector(token.approve.selector, spender, value)
                                    );
                                }
                            
                                function safeIncreaseAllowance(
                                    IERC20 token,
                                    address spender,
                                    uint256 value
                                ) internal {
                                    uint256 newAllowance = token.allowance(address(this), spender).add(
                                        value
                                    );
                                    _callOptionalReturn(
                                        token,
                                        abi.encodeWithSelector(
                                            token.approve.selector,
                                            spender,
                                            newAllowance
                                        )
                                    );
                                }
                            
                                function safeDecreaseAllowance(
                                    IERC20 token,
                                    address spender,
                                    uint256 value
                                ) internal {
                                    uint256 newAllowance = token.allowance(address(this), spender).sub(
                                        value,
                                        "SafeERC20: decreased allowance below zero"
                                    );
                                    _callOptionalReturn(
                                        token,
                                        abi.encodeWithSelector(
                                            token.approve.selector,
                                            spender,
                                            newAllowance
                                        )
                                    );
                                }
                            
                                /**
                                 * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                                 * on the return value: the return value is optional (but if data is returned, it must not be false).
                                 * @param token The token targeted by the call.
                                 * @param data The call data (encoded using abi.encode or one of its variants).
                                 */
                                function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                    // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                    // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                                    // the target address contains contract code and also asserts for success in the low-level call.
                            
                                    bytes memory returndata = address(token).functionCall(
                                        data,
                                        "SafeERC20: low-level call failed"
                                    );
                                    if (returndata.length > 0) {
                                        // Return data is optional
                                        // solhint-disable-next-line max-line-length
                                        require(
                                            abi.decode(returndata, (bool)),
                                            "SafeERC20: ERC20 operation did not succeed"
                                        );
                                    }
                                }
                            }
                            
                            // File: contracts/v1.1/Rescuable.sol
                            
                            /**
                             * Copyright (c) 2018-2020 CENTRE SECZ
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            
                            pragma solidity 0.6.12;
                            
                            contract Rescuable is Ownable {
                                using SafeERC20 for IERC20;
                            
                                address private _rescuer;
                            
                                event RescuerChanged(address indexed newRescuer);
                            
                                /**
                                 * @notice Returns current rescuer
                                 * @return Rescuer's address
                                 */
                                function rescuer() external view returns (address) {
                                    return _rescuer;
                                }
                            
                                /**
                                 * @notice Revert if called by any account other than the rescuer.
                                 */
                                modifier onlyRescuer() {
                                    require(msg.sender == _rescuer, "Rescuable: caller is not the rescuer");
                                    _;
                                }
                            
                                /**
                                 * @notice Rescue ERC20 tokens locked up in this contract.
                                 * @param tokenContract ERC20 token contract address
                                 * @param to        Recipient address
                                 * @param amount    Amount to withdraw
                                 */
                                function rescueERC20(
                                    IERC20 tokenContract,
                                    address to,
                                    uint256 amount
                                ) external onlyRescuer {
                                    tokenContract.safeTransfer(to, amount);
                                }
                            
                                /**
                                 * @notice Assign the rescuer role to a given address.
                                 * @param newRescuer New rescuer's address
                                 */
                                function updateRescuer(address newRescuer) external onlyOwner {
                                    require(
                                        newRescuer != address(0),
                                        "Rescuable: new rescuer is the zero address"
                                    );
                                    _rescuer = newRescuer;
                                    emit RescuerChanged(newRescuer);
                                }
                            }
                            
                            // File: contracts/v1.1/FiatTokenV1_1.sol
                            
                            /**
                             * Copyright (c) 2018-2020 CENTRE SECZ
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            
                            pragma solidity 0.6.12;
                            
                            /**
                             * @title FiatTokenV1_1
                             * @dev ERC20 Token backed by fiat reserves
                             */
                            contract FiatTokenV1_1 is FiatTokenV1, Rescuable {
                            
                            }
                            
                            // File: contracts/v2/AbstractFiatTokenV2.sol
                            
                            /**
                             * Copyright (c) 2018-2020 CENTRE SECZ
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            
                            pragma solidity 0.6.12;
                            
                            abstract contract AbstractFiatTokenV2 is AbstractFiatTokenV1 {
                                function _increaseAllowance(
                                    address owner,
                                    address spender,
                                    uint256 increment
                                ) internal virtual;
                            
                                function _decreaseAllowance(
                                    address owner,
                                    address spender,
                                    uint256 decrement
                                ) internal virtual;
                            }
                            
                            // File: contracts/util/ECRecover.sol
                            
                            /**
                             * Copyright (c) 2016-2019 zOS Global Limited
                             * Copyright (c) 2018-2020 CENTRE SECZ
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            
                            pragma solidity 0.6.12;
                            
                            /**
                             * @title ECRecover
                             * @notice A library that provides a safe ECDSA recovery function
                             */
                            library ECRecover {
                                /**
                                 * @notice Recover signer's address from a signed message
                                 * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol
                                 * Modifications: Accept v, r, and s as separate arguments
                                 * @param digest    Keccak-256 hash digest of the signed message
                                 * @param v         v of the signature
                                 * @param r         r of the signature
                                 * @param s         s of the signature
                                 * @return Signer address
                                 */
                                function recover(
                                    bytes32 digest,
                                    uint8 v,
                                    bytes32 r,
                                    bytes32 s
                                ) internal pure returns (address) {
                                    // 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 (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): 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.
                                    if (
                                        uint256(s) >
                                        0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
                                    ) {
                                        revert("ECRecover: invalid signature 's' value");
                                    }
                            
                                    if (v != 27 && v != 28) {
                                        revert("ECRecover: invalid signature 'v' value");
                                    }
                            
                                    // If the signature is valid (and not malleable), return the signer address
                                    address signer = ecrecover(digest, v, r, s);
                                    require(signer != address(0), "ECRecover: invalid signature");
                            
                                    return signer;
                                }
                            }
                            
                            // File: contracts/util/EIP712.sol
                            
                            /**
                             * Copyright (c) 2018-2020 CENTRE SECZ
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            
                            pragma solidity 0.6.12;
                            
                            /**
                             * @title EIP712
                             * @notice A library that provides EIP712 helper functions
                             */
                            library EIP712 {
                                /**
                                 * @notice Make EIP712 domain separator
                                 * @param name      Contract name
                                 * @param version   Contract version
                                 * @return Domain separator
                                 */
                                function makeDomainSeparator(string memory name, string memory version)
                                    internal
                                    view
                                    returns (bytes32)
                                {
                                    uint256 chainId;
                                    assembly {
                                        chainId := chainid()
                                    }
                                    return
                                        keccak256(
                                            abi.encode(
                                                // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
                                                0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
                                                keccak256(bytes(name)),
                                                keccak256(bytes(version)),
                                                chainId,
                                                address(this)
                                            )
                                        );
                                }
                            
                                /**
                                 * @notice Recover signer's address from a EIP712 signature
                                 * @param domainSeparator   Domain separator
                                 * @param v                 v of the signature
                                 * @param r                 r of the signature
                                 * @param s                 s of the signature
                                 * @param typeHashAndData   Type hash concatenated with data
                                 * @return Signer's address
                                 */
                                function recover(
                                    bytes32 domainSeparator,
                                    uint8 v,
                                    bytes32 r,
                                    bytes32 s,
                                    bytes memory typeHashAndData
                                ) internal pure returns (address) {
                                    bytes32 digest = keccak256(
                                        abi.encodePacked(
                                            "\x19\x01",
                                            domainSeparator,
                                            keccak256(typeHashAndData)
                                        )
                                    );
                                    return ECRecover.recover(digest, v, r, s);
                                }
                            }
                            
                            // File: contracts/v2/EIP712Domain.sol
                            
                            /**
                             * Copyright (c) 2018-2020 CENTRE SECZ
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            
                            pragma solidity 0.6.12;
                            
                            /**
                             * @title EIP712 Domain
                             */
                            contract EIP712Domain {
                                /**
                                 * @dev EIP712 Domain Separator
                                 */
                                bytes32 public DOMAIN_SEPARATOR;
                            }
                            
                            // File: contracts/v2/EIP3009.sol
                            
                            /**
                             * Copyright (c) 2018-2020 CENTRE SECZ
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            
                            pragma solidity 0.6.12;
                            
                            /**
                             * @title EIP-3009
                             * @notice Provide internal implementation for gas-abstracted transfers
                             * @dev Contracts that inherit from this must wrap these with publicly
                             * accessible functions, optionally adding modifiers where necessary
                             */
                            abstract contract EIP3009 is AbstractFiatTokenV2, EIP712Domain {
                                // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
                                bytes32
                                    public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
                            
                                // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
                                bytes32
                                    public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;
                            
                                // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)")
                                bytes32
                                    public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;
                            
                                /**
                                 * @dev authorizer address => nonce => bool (true if nonce is used)
                                 */
                                mapping(address => mapping(bytes32 => bool)) private _authorizationStates;
                            
                                event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
                                event AuthorizationCanceled(
                                    address indexed authorizer,
                                    bytes32 indexed nonce
                                );
                            
                                /**
                                 * @notice Returns the state of an authorization
                                 * @dev Nonces are randomly generated 32-byte data unique to the
                                 * authorizer's address
                                 * @param authorizer    Authorizer's address
                                 * @param nonce         Nonce of the authorization
                                 * @return True if the nonce is used
                                 */
                                function authorizationState(address authorizer, bytes32 nonce)
                                    external
                                    view
                                    returns (bool)
                                {
                                    return _authorizationStates[authorizer][nonce];
                                }
                            
                                /**
                                 * @notice Execute a transfer with a signed authorization
                                 * @param from          Payer's address (Authorizer)
                                 * @param to            Payee's address
                                 * @param value         Amount to be transferred
                                 * @param validAfter    The time after which this is valid (unix time)
                                 * @param validBefore   The time before which this is valid (unix time)
                                 * @param nonce         Unique nonce
                                 * @param v             v of the signature
                                 * @param r             r of the signature
                                 * @param s             s of the signature
                                 */
                                function _transferWithAuthorization(
                                    address from,
                                    address to,
                                    uint256 value,
                                    uint256 validAfter,
                                    uint256 validBefore,
                                    bytes32 nonce,
                                    uint8 v,
                                    bytes32 r,
                                    bytes32 s
                                ) internal {
                                    _requireValidAuthorization(from, nonce, validAfter, validBefore);
                            
                                    bytes memory data = abi.encode(
                                        TRANSFER_WITH_AUTHORIZATION_TYPEHASH,
                                        from,
                                        to,
                                        value,
                                        validAfter,
                                        validBefore,
                                        nonce
                                    );
                                    require(
                                        EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from,
                                        "FiatTokenV2: invalid signature"
                                    );
                            
                                    _markAuthorizationAsUsed(from, nonce);
                                    _transfer(from, to, value);
                                }
                            
                                /**
                                 * @notice Receive a transfer with a signed authorization from the payer
                                 * @dev This has an additional check to ensure that the payee's address
                                 * matches the caller of this function to prevent front-running attacks.
                                 * @param from          Payer's address (Authorizer)
                                 * @param to            Payee's address
                                 * @param value         Amount to be transferred
                                 * @param validAfter    The time after which this is valid (unix time)
                                 * @param validBefore   The time before which this is valid (unix time)
                                 * @param nonce         Unique nonce
                                 * @param v             v of the signature
                                 * @param r             r of the signature
                                 * @param s             s of the signature
                                 */
                                function _receiveWithAuthorization(
                                    address from,
                                    address to,
                                    uint256 value,
                                    uint256 validAfter,
                                    uint256 validBefore,
                                    bytes32 nonce,
                                    uint8 v,
                                    bytes32 r,
                                    bytes32 s
                                ) internal {
                                    require(to == msg.sender, "FiatTokenV2: caller must be the payee");
                                    _requireValidAuthorization(from, nonce, validAfter, validBefore);
                            
                                    bytes memory data = abi.encode(
                                        RECEIVE_WITH_AUTHORIZATION_TYPEHASH,
                                        from,
                                        to,
                                        value,
                                        validAfter,
                                        validBefore,
                                        nonce
                                    );
                                    require(
                                        EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from,
                                        "FiatTokenV2: invalid signature"
                                    );
                            
                                    _markAuthorizationAsUsed(from, nonce);
                                    _transfer(from, to, value);
                                }
                            
                                /**
                                 * @notice Attempt to cancel an authorization
                                 * @param authorizer    Authorizer's address
                                 * @param nonce         Nonce of the authorization
                                 * @param v             v of the signature
                                 * @param r             r of the signature
                                 * @param s             s of the signature
                                 */
                                function _cancelAuthorization(
                                    address authorizer,
                                    bytes32 nonce,
                                    uint8 v,
                                    bytes32 r,
                                    bytes32 s
                                ) internal {
                                    _requireUnusedAuthorization(authorizer, nonce);
                            
                                    bytes memory data = abi.encode(
                                        CANCEL_AUTHORIZATION_TYPEHASH,
                                        authorizer,
                                        nonce
                                    );
                                    require(
                                        EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == authorizer,
                                        "FiatTokenV2: invalid signature"
                                    );
                            
                                    _authorizationStates[authorizer][nonce] = true;
                                    emit AuthorizationCanceled(authorizer, nonce);
                                }
                            
                                /**
                                 * @notice Check that an authorization is unused
                                 * @param authorizer    Authorizer's address
                                 * @param nonce         Nonce of the authorization
                                 */
                                function _requireUnusedAuthorization(address authorizer, bytes32 nonce)
                                    private
                                    view
                                {
                                    require(
                                        !_authorizationStates[authorizer][nonce],
                                        "FiatTokenV2: authorization is used or canceled"
                                    );
                                }
                            
                                /**
                                 * @notice Check that authorization is valid
                                 * @param authorizer    Authorizer's address
                                 * @param nonce         Nonce of the authorization
                                 * @param validAfter    The time after which this is valid (unix time)
                                 * @param validBefore   The time before which this is valid (unix time)
                                 */
                                function _requireValidAuthorization(
                                    address authorizer,
                                    bytes32 nonce,
                                    uint256 validAfter,
                                    uint256 validBefore
                                ) private view {
                                    require(
                                        now > validAfter,
                                        "FiatTokenV2: authorization is not yet valid"
                                    );
                                    require(now < validBefore, "FiatTokenV2: authorization is expired");
                                    _requireUnusedAuthorization(authorizer, nonce);
                                }
                            
                                /**
                                 * @notice Mark an authorization as used
                                 * @param authorizer    Authorizer's address
                                 * @param nonce         Nonce of the authorization
                                 */
                                function _markAuthorizationAsUsed(address authorizer, bytes32 nonce)
                                    private
                                {
                                    _authorizationStates[authorizer][nonce] = true;
                                    emit AuthorizationUsed(authorizer, nonce);
                                }
                            }
                            
                            // File: contracts/v2/EIP2612.sol
                            
                            /**
                             * Copyright (c) 2018-2020 CENTRE SECZ
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            
                            pragma solidity 0.6.12;
                            
                            /**
                             * @title EIP-2612
                             * @notice Provide internal implementation for gas-abstracted approvals
                             */
                            abstract contract EIP2612 is AbstractFiatTokenV2, EIP712Domain {
                                // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
                                bytes32
                                    public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                            
                                mapping(address => uint256) private _permitNonces;
                            
                                /**
                                 * @notice Nonces for permit
                                 * @param owner Token owner's address (Authorizer)
                                 * @return Next nonce
                                 */
                                function nonces(address owner) external view returns (uint256) {
                                    return _permitNonces[owner];
                                }
                            
                                /**
                                 * @notice Verify a signed approval permit and execute if valid
                                 * @param owner     Token owner's address (Authorizer)
                                 * @param spender   Spender's address
                                 * @param value     Amount of allowance
                                 * @param deadline  The time at which this expires (unix time)
                                 * @param v         v of the signature
                                 * @param r         r of the signature
                                 * @param s         s of the signature
                                 */
                                function _permit(
                                    address owner,
                                    address spender,
                                    uint256 value,
                                    uint256 deadline,
                                    uint8 v,
                                    bytes32 r,
                                    bytes32 s
                                ) internal {
                                    require(deadline >= now, "FiatTokenV2: permit is expired");
                            
                                    bytes memory data = abi.encode(
                                        PERMIT_TYPEHASH,
                                        owner,
                                        spender,
                                        value,
                                        _permitNonces[owner]++,
                                        deadline
                                    );
                                    require(
                                        EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner,
                                        "EIP2612: invalid signature"
                                    );
                            
                                    _approve(owner, spender, value);
                                }
                            }
                            
                            // File: contracts/v2/FiatTokenV2.sol
                            
                            /**
                             * Copyright (c) 2018-2020 CENTRE SECZ
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            
                            pragma solidity 0.6.12;
                            
                            /**
                             * @title FiatToken V2
                             * @notice ERC20 Token backed by fiat reserves, version 2
                             */
                            contract FiatTokenV2 is FiatTokenV1_1, EIP3009, EIP2612 {
                                uint8 internal _initializedVersion;
                            
                                /**
                                 * @notice Initialize v2
                                 * @param newName   New token name
                                 */
                                function initializeV2(string calldata newName) external {
                                    // solhint-disable-next-line reason-string
                                    require(initialized && _initializedVersion == 0);
                                    name = newName;
                                    DOMAIN_SEPARATOR = EIP712.makeDomainSeparator(newName, "2");
                                    _initializedVersion = 1;
                                }
                            
                                /**
                                 * @notice Increase the allowance by a given increment
                                 * @param spender   Spender's address
                                 * @param increment Amount of increase in allowance
                                 * @return True if successful
                                 */
                                function increaseAllowance(address spender, uint256 increment)
                                    external
                                    whenNotPaused
                                    notBlacklisted(msg.sender)
                                    notBlacklisted(spender)
                                    returns (bool)
                                {
                                    _increaseAllowance(msg.sender, spender, increment);
                                    return true;
                                }
                            
                                /**
                                 * @notice Decrease the allowance by a given decrement
                                 * @param spender   Spender's address
                                 * @param decrement Amount of decrease in allowance
                                 * @return True if successful
                                 */
                                function decreaseAllowance(address spender, uint256 decrement)
                                    external
                                    whenNotPaused
                                    notBlacklisted(msg.sender)
                                    notBlacklisted(spender)
                                    returns (bool)
                                {
                                    _decreaseAllowance(msg.sender, spender, decrement);
                                    return true;
                                }
                            
                                /**
                                 * @notice Execute a transfer with a signed authorization
                                 * @param from          Payer's address (Authorizer)
                                 * @param to            Payee's address
                                 * @param value         Amount to be transferred
                                 * @param validAfter    The time after which this is valid (unix time)
                                 * @param validBefore   The time before which this is valid (unix time)
                                 * @param nonce         Unique nonce
                                 * @param v             v of the signature
                                 * @param r             r of the signature
                                 * @param s             s of the signature
                                 */
                                function transferWithAuthorization(
                                    address from,
                                    address to,
                                    uint256 value,
                                    uint256 validAfter,
                                    uint256 validBefore,
                                    bytes32 nonce,
                                    uint8 v,
                                    bytes32 r,
                                    bytes32 s
                                ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                                    _transferWithAuthorization(
                                        from,
                                        to,
                                        value,
                                        validAfter,
                                        validBefore,
                                        nonce,
                                        v,
                                        r,
                                        s
                                    );
                                }
                            
                                /**
                                 * @notice Receive a transfer with a signed authorization from the payer
                                 * @dev This has an additional check to ensure that the payee's address
                                 * matches the caller of this function to prevent front-running attacks.
                                 * @param from          Payer's address (Authorizer)
                                 * @param to            Payee's address
                                 * @param value         Amount to be transferred
                                 * @param validAfter    The time after which this is valid (unix time)
                                 * @param validBefore   The time before which this is valid (unix time)
                                 * @param nonce         Unique nonce
                                 * @param v             v of the signature
                                 * @param r             r of the signature
                                 * @param s             s of the signature
                                 */
                                function receiveWithAuthorization(
                                    address from,
                                    address to,
                                    uint256 value,
                                    uint256 validAfter,
                                    uint256 validBefore,
                                    bytes32 nonce,
                                    uint8 v,
                                    bytes32 r,
                                    bytes32 s
                                ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                                    _receiveWithAuthorization(
                                        from,
                                        to,
                                        value,
                                        validAfter,
                                        validBefore,
                                        nonce,
                                        v,
                                        r,
                                        s
                                    );
                                }
                            
                                /**
                                 * @notice Attempt to cancel an authorization
                                 * @dev Works only if the authorization is not yet used.
                                 * @param authorizer    Authorizer's address
                                 * @param nonce         Nonce of the authorization
                                 * @param v             v of the signature
                                 * @param r             r of the signature
                                 * @param s             s of the signature
                                 */
                                function cancelAuthorization(
                                    address authorizer,
                                    bytes32 nonce,
                                    uint8 v,
                                    bytes32 r,
                                    bytes32 s
                                ) external whenNotPaused {
                                    _cancelAuthorization(authorizer, nonce, v, r, s);
                                }
                            
                                /**
                                 * @notice Update allowance with a signed permit
                                 * @param owner       Token owner's address (Authorizer)
                                 * @param spender     Spender's address
                                 * @param value       Amount of allowance
                                 * @param deadline    Expiration time, seconds since the epoch
                                 * @param v           v of the signature
                                 * @param r           r of the signature
                                 * @param s           s of the signature
                                 */
                                function permit(
                                    address owner,
                                    address spender,
                                    uint256 value,
                                    uint256 deadline,
                                    uint8 v,
                                    bytes32 r,
                                    bytes32 s
                                ) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) {
                                    _permit(owner, spender, value, deadline, v, r, s);
                                }
                            
                                /**
                                 * @notice Internal function to increase the allowance by a given increment
                                 * @param owner     Token owner's address
                                 * @param spender   Spender's address
                                 * @param increment Amount of increase
                                 */
                                function _increaseAllowance(
                                    address owner,
                                    address spender,
                                    uint256 increment
                                ) internal override {
                                    _approve(owner, spender, allowed[owner][spender].add(increment));
                                }
                            
                                /**
                                 * @notice Internal function to decrease the allowance by a given decrement
                                 * @param owner     Token owner's address
                                 * @param spender   Spender's address
                                 * @param decrement Amount of decrease
                                 */
                                function _decreaseAllowance(
                                    address owner,
                                    address spender,
                                    uint256 decrement
                                ) internal override {
                                    _approve(
                                        owner,
                                        spender,
                                        allowed[owner][spender].sub(
                                            decrement,
                                            "ERC20: decreased allowance below zero"
                                        )
                                    );
                                }
                            }
                            
                            // File: contracts/v2/FiatTokenV2_1.sol
                            
                            /**
                             * Copyright (c) 2018-2020 CENTRE SECZ
                             *
                             * Permission is hereby granted, free of charge, to any person obtaining a copy
                             * of this software and associated documentation files (the "Software"), to deal
                             * in the Software without restriction, including without limitation the rights
                             * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                             * copies of the Software, and to permit persons to whom the Software is
                             * furnished to do so, subject to the following conditions:
                             *
                             * The above copyright notice and this permission notice shall be included in
                             * copies or substantial portions of the Software.
                             *
                             * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                             * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                             * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                             * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                             * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                             * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                             * SOFTWARE.
                             */
                            
                            pragma solidity 0.6.12;
                            
                            // solhint-disable func-name-mixedcase
                            
                            /**
                             * @title FiatToken V2.1
                             * @notice ERC20 Token backed by fiat reserves, version 2.1
                             */
                            contract FiatTokenV2_1 is FiatTokenV2 {
                                /**
                                 * @notice Initialize v2.1
                                 * @param lostAndFound  The address to which the locked funds are sent
                                 */
                                function initializeV2_1(address lostAndFound) external {
                                    // solhint-disable-next-line reason-string
                                    require(_initializedVersion == 1);
                            
                                    uint256 lockedAmount = balances[address(this)];
                                    if (lockedAmount > 0) {
                                        _transfer(address(this), lostAndFound, lockedAmount);
                                    }
                                    blacklisted[address(this)] = true;
                            
                                    _initializedVersion = 2;
                                }
                            
                                /**
                                 * @notice Version string for the EIP712 domain separator
                                 * @return Version string
                                 */
                                function version() external view returns (string memory) {
                                    return "2";
                                }
                            }