ETH Price: $2,530.07 (+0.57%)

Transaction Decoder

Block:
14855430 at May-27-2022 05:31:29 PM +UTC
Transaction Fee:
0.00975532 ETH $24.68
Gas Used:
243,883 Gas / 40 Gwei

Emitted Events:

162 AppProxyUpgradeable.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000cfdca4f2aab26090f80ea0aafadb83779f93530c, 0x000000000000000000000000def171fe48cf0115b1d80b88dc8eab59176fee57, 00000000000000000000000000000000000000000000000009213f6b5802d585 )
163 AppProxyUpgradeable.0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925( 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, 0x000000000000000000000000cfdca4f2aab26090f80ea0aafadb83779f93530c, 0x000000000000000000000000216b4b4ba9f3e719726886d34a177484278bfcae, ffffffffffffffffffffffffffffffffffffffffffffffffe370f3ff8a712a7a )
164 AppProxyUpgradeable.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000def171fe48cf0115b1d80b88dc8eab59176fee57, 0x0000000000000000000000004028daac072e492d34a3afdbef0ba7e35d8b55c4, 00000000000000000000000000000000000000000000000009213f6b5802d585 )
165 AppProxyUpgradeable.0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925( 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, 0x000000000000000000000000def171fe48cf0115b1d80b88dc8eab59176fee57, 0x000000000000000000000000f9234cb08edb93c0d4a4d4c70cc3ffd070e78e07, ffffffffffffffffffffffffffffffffffffffffffffffa4521851bfb8f465c4 )
166 WETH9.Transfer( src=UniswapV2Pair, dst=NewUniswapV2ExchangeRouter, wad=635865677133225618 )
167 UniswapV2Pair.Sync( reserve0=918220020259290944594, reserve1=889620404955967038003 )
168 UniswapV2Pair.Swap( sender=NewUniswapV2ExchangeRouter, amount0In=657876750843434372, amount1In=0, amount0Out=0, amount1Out=635865677133225618, to=NewUniswapV2ExchangeRouter )
169 WETH9.Withdrawal( src=NewUniswapV2ExchangeRouter, wad=635865677133225618 )
170 GnosisSafeProxy.0x3d0ce9bfc3ed7d6862dbb28b2dea94561fe714a1b4d019aa8af39730d1ad7c3d( 0x3d0ce9bfc3ed7d6862dbb28b2dea94561fe714a1b4d019aa8af39730d1ad7c3d, 0x000000000000000000000000def171fe48cf0115b1d80b88dc8eab59176fee57, 00000000000000000000000000000000000000000000000000033819d8a13adf )
171 AugustusSwapper.0x974dd0442e0b8c00fdbaae504edea1412d63bc110294a98b3c61ddcd0e703aa8( 0x974dd0442e0b8c00fdbaae504edea1412d63bc110294a98b3c61ddcd0e703aa8, 0x000000000000000000000000cfdca4f2aab26090f80ea0aafadb83779f93530c, 0x000000000000000000000000ae7ab96520de3a18e5e111b5eaab095312d7fe84, 0x000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, 97e731990ee9401197587bb5c027e22200000000000000000000000000000000, 000000000000000000000000558247e365be655f9144e1a0140d793984372ef3, 010000000000000000000000000000000000000000000000000000000000405f, 000000000000000000000000cfdca4f2aab26090f80ea0aafadb83779f93530c, 00000000000000000000000000000000000000000000000009213f6b5802d585, 00000000000000000000000000000000000000000000000008d30c76e2639e92, 00000000000000000000000000000000000000000000000008d30c76e2639e92 )

Account State Difference:

  Address   Before After State Difference Code
0x4028DAAC...35D8b55C4
0x558247e3...984372Ef3 207.936643228454991091 Eth207.941777843797841887 Eth0.005134615342850796
0xae7ab965...312D7fE84
0xb1720612...925282fCa 73.03349296542178514 Eth73.034399074011699987 Eth0.000906108589914847
0xC02aaA39...83C756Cc2 5,834,869.958016892977875663 Eth5,834,869.322151215844650045 Eth0.635865677133225618
(Ezil.me : Ezil Pool 4)
414.545478497337808006 Eth414.545900565296554369 Eth0.000422067958746363
0xcFdcA4f2...79f93530C
0.541509706410240801 Eth
Nonce: 36
1.161579339610700776 Eth
Nonce: 37
0.620069633200459975

Execution Trace

AugustusSwapper.54e3f31b( )
  • SimpleSwap.simpleSwap( data=[{name:fromToken, type:address, order:1, indexed:false, value:0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84, valueString:0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84}, {name:toToken, type:address, order:2, indexed:false, value:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, valueString:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE}, {name:fromAmount, type:uint256, order:3, indexed:false, value:657876750843434373, valueString:657876750843434373}, {name:toAmount, type:uint256, order:4, indexed:false, value:629507020361893361, valueString:629507020361893361}, {name:expectedAmount, type:uint256, order:5, indexed:false, value:635865677133225618, valueString:635865677133225618}, {name:callees, type:address[], order:6, indexed:false, value:[0xF9234CB08edb93c0d4a4d4c70cC3FfD070e78e07], valueString:[0xF9234CB08edb93c0d4a4d4c70cC3FfD070e78e07]}, {name:exchangeData, type:bytes, order:7, indexed:false, value:0x91A32B69000000000000000000000000AE7AB96520DE3A18E5E111B5EAAB095312D7FE8400000000000000000000000000000000000000000000000009213F6B5802D5850000000000000000000000000000000000000000000000000000000000000001000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC200000000000000000000000000000000000000000000000000000000000000A00000000000000000000000000000000000000000000000000000000000000001000000000000000000004DE24028DAAC072E492D34A3AFDBEF0BA7E35D8B55C4, valueString:0x91A32B69000000000000000000000000AE7AB96520DE3A18E5E111B5EAAB095312D7FE8400000000000000000000000000000000000000000000000009213F6B5802D5850000000000000000000000000000000000000000000000000000000000000001000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC200000000000000000000000000000000000000000000000000000000000000A00000000000000000000000000000000000000000000000000000000000000001000000000000000000004DE24028DAAC072E492D34A3AFDBEF0BA7E35D8B55C4}, {name:startIndexes, type:uint256[], order:8, indexed:false, value:[0, 228], valueString:[0, 228]}, {name:values, type:uint256[], order:9, indexed:false, value:[0], valueString:[0]}, {name:beneficiary, type:address, order:10, indexed:false, value:0x0000000000000000000000000000000000000000, valueString:0x0000000000000000000000000000000000000000}, {name:partner, type:address, order:11, indexed:false, value:0x558247e365be655f9144e1a0140D793984372Ef3, valueString:0x558247e365be655f9144e1a0140D793984372Ef3}, {name:feePercent, type:uint256, order:12, indexed:false, value:452312848583266388373324160190187140051835877600158453279131187530910679135, valueString:452312848583266388373324160190187140051835877600158453279131187530910679135}, {name:permit, type:bytes, order:13, indexed:false, value:0x, valueString:0x}, {name:deadline, type:uint256, order:14, indexed:false, value:1653694174, valueString:1653694174}, {name:uuid, type:bytes16, order:15, indexed:false, value:l+cxmQ7pQBGXWHu1wCfiIg==, valueString:System.Byte[]}] ) => ( receivedAmount=635865677133225618 )
    • TokenTransferProxy.transferFrom( token=0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84, from=0xcFdcA4f2AAB26090f80Ea0AaFADB83779f93530C, to=0xDEF171Fe48CF0115B1d80b88dc8eAB59176FEe57, amount=657876750843434373 )
      • AppProxyUpgradeable.23b872dd( )
        • KernelProxy.be00bbd8( )
          • Kernel.getApp( _namespace=F1F3EB40F5BC1AD1344716CED8B8A0431D840B5783AEA1FD01786BC26F35AC0F, _appId=3CA7C3E38968823CCB4C78EA688DF41356F182AE1D159E4EE608D30D68CEF320 ) => ( 0xC7B5aF82B05Eb3b64F12241B04B2cF14469E39F7 )
          • Lido.transferFrom( _sender=0xcFdcA4f2AAB26090f80Ea0AaFADB83779f93530C, _recipient=0xDEF171Fe48CF0115B1d80b88dc8eAB59176FEe57, _amount=657876750843434373 ) => ( True )
          • NewUniswapV2ExchangeRouter.swap( tokenIn=0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84, amountIn=657876750843434373, amountOutMin=1, weth=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, pools=[29139785931591699495259503408512656925440107917039044] ) => ( tokensBought=635865677133225618 )
            • AppProxyUpgradeable.23b872dd( )
              • KernelProxy.be00bbd8( )
                • Kernel.getApp( _namespace=F1F3EB40F5BC1AD1344716CED8B8A0431D840B5783AEA1FD01786BC26F35AC0F, _appId=3CA7C3E38968823CCB4C78EA688DF41356F182AE1D159E4EE608D30D68CEF320 ) => ( 0xC7B5aF82B05Eb3b64F12241B04B2cF14469E39F7 )
                • Lido.transferFrom( _sender=0xDEF171Fe48CF0115B1d80b88dc8eAB59176FEe57, _recipient=0x4028DAAC072e492d34a3Afdbef0ba7e35D8b55C4, _amount=657876750843434373 ) => ( True )
                • UniswapV2Pair.STATICCALL( )
                • UniswapV2Pair.swap( amount0Out=0, amount1Out=635865677133225618, to=0xF9234CB08edb93c0d4a4d4c70cC3FfD070e78e07, data=0x )
                  • WETH9.transfer( dst=0xF9234CB08edb93c0d4a4d4c70cC3FfD070e78e07, wad=635865677133225618 ) => ( True )
                  • AppProxyUpgradeable.70a08231( )
                    • KernelProxy.be00bbd8( )
                      • Kernel.getApp( _namespace=F1F3EB40F5BC1AD1344716CED8B8A0431D840B5783AEA1FD01786BC26F35AC0F, _appId=3CA7C3E38968823CCB4C78EA688DF41356F182AE1D159E4EE608D30D68CEF320 ) => ( 0xC7B5aF82B05Eb3b64F12241B04B2cF14469E39F7 )
                      • Lido.balanceOf( _account=0x4028DAAC072e492d34a3Afdbef0ba7e35D8b55C4 ) => ( 918220020259290944594 )
                      • WETH9.balanceOf( 0x4028DAAC072e492d34a3Afdbef0ba7e35D8b55C4 ) => ( 889620404955967038003 )
                      • WETH9.withdraw( wad=635865677133225618 )
                        • ETH 0.635865677133225618 NewUniswapV2ExchangeRouter.CALL( )
                        • ETH 0.635865677133225618 AugustusSwapper.CALL( )
                        • ETH 0.005134615342850796 0x558247e365be655f9144e1a0140d793984372ef3.CALL( )
                        • ETH 0.000906108589914847 GnosisSafeProxy.CALL( )
                          • ETH 0.000906108589914847 GnosisSafe.DELEGATECALL( )
                          • ETH 0.629824953200459975 0xcfdca4f2aab26090f80ea0aafadb83779f93530c.CALL( )
                            File 1 of 12: AugustusSwapper
                            // File: openzeppelin-solidity/contracts/utils/EnumerableSet.sol
                            pragma solidity >=0.6.0 <0.8.0;
                            /**
                             * @dev Library for managing
                             * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
                             * types.
                             *
                             * Sets have the following properties:
                             *
                             * - Elements are added, removed, and checked for existence in constant time
                             * (O(1)).
                             * - Elements are enumerated in O(n). No guarantees are made on the ordering.
                             *
                             * ```
                             * contract Example {
                             *     // Add the library methods
                             *     using EnumerableSet for EnumerableSet.AddressSet;
                             *
                             *     // Declare a set state variable
                             *     EnumerableSet.AddressSet private mySet;
                             * }
                             * ```
                             *
                             * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
                             * and `uint256` (`UintSet`) are supported.
                             */
                            library EnumerableSet {
                                // To implement this library for multiple types with as little code
                                // repetition as possible, we write it in terms of a generic Set type with
                                // bytes32 values.
                                // The Set implementation uses private functions, and user-facing
                                // implementations (such as AddressSet) are just wrappers around the
                                // underlying Set.
                                // This means that we can only create new EnumerableSets for types that fit
                                // in bytes32.
                                struct Set {
                                    // Storage of set values
                                    bytes32[] _values;
                                    // Position of the value in the `values` array, plus 1 because index 0
                                    // means a value is not in the set.
                                    mapping (bytes32 => uint256) _indexes;
                                }
                                /**
                                 * @dev Add a value to a set. O(1).
                                 *
                                 * Returns true if the value was added to the set, that is if it was not
                                 * already present.
                                 */
                                function _add(Set storage set, bytes32 value) private returns (bool) {
                                    if (!_contains(set, value)) {
                                        set._values.push(value);
                                        // The value is stored at length-1, but we add 1 to all indexes
                                        // and use 0 as a sentinel value
                                        set._indexes[value] = set._values.length;
                                        return true;
                                    } else {
                                        return false;
                                    }
                                }
                                /**
                                 * @dev Removes a value from a set. O(1).
                                 *
                                 * Returns true if the value was removed from the set, that is if it was
                                 * present.
                                 */
                                function _remove(Set storage set, bytes32 value) private returns (bool) {
                                    // We read and store the value's index to prevent multiple reads from the same storage slot
                                    uint256 valueIndex = set._indexes[value];
                                    if (valueIndex != 0) { // Equivalent to contains(set, value)
                                        // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                                        // the array, and then remove the last element (sometimes called as 'swap and pop').
                                        // This modifies the order of the array, as noted in {at}.
                                        uint256 toDeleteIndex = valueIndex - 1;
                                        uint256 lastIndex = set._values.length - 1;
                                        // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
                                        // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
                                        bytes32 lastvalue = set._values[lastIndex];
                                        // Move the last value to the index where the value to delete is
                                        set._values[toDeleteIndex] = lastvalue;
                                        // Update the index for the moved value
                                        set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
                                        // Delete the slot where the moved value was stored
                                        set._values.pop();
                                        // Delete the index for the deleted slot
                                        delete set._indexes[value];
                                        return true;
                                    } else {
                                        return false;
                                    }
                                }
                                /**
                                 * @dev Returns true if the value is in the set. O(1).
                                 */
                                function _contains(Set storage set, bytes32 value) private view returns (bool) {
                                    return set._indexes[value] != 0;
                                }
                                /**
                                 * @dev Returns the number of values on the set. O(1).
                                 */
                                function _length(Set storage set) private view returns (uint256) {
                                    return set._values.length;
                                }
                               /**
                                * @dev Returns the value stored at position `index` in the set. O(1).
                                *
                                * Note that there are no guarantees on the ordering of values inside the
                                * array, and it may change when more values are added or removed.
                                *
                                * Requirements:
                                *
                                * - `index` must be strictly less than {length}.
                                */
                                function _at(Set storage set, uint256 index) private view returns (bytes32) {
                                    require(set._values.length > index, "EnumerableSet: index out of bounds");
                                    return set._values[index];
                                }
                                // Bytes32Set
                                struct Bytes32Set {
                                    Set _inner;
                                }
                                /**
                                 * @dev Add a value to a set. O(1).
                                 *
                                 * Returns true if the value was added to the set, that is if it was not
                                 * already present.
                                 */
                                function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                                    return _add(set._inner, value);
                                }
                                /**
                                 * @dev Removes a value from a set. O(1).
                                 *
                                 * Returns true if the value was removed from the set, that is if it was
                                 * present.
                                 */
                                function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                                    return _remove(set._inner, value);
                                }
                                /**
                                 * @dev Returns true if the value is in the set. O(1).
                                 */
                                function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                                    return _contains(set._inner, value);
                                }
                                /**
                                 * @dev Returns the number of values in the set. O(1).
                                 */
                                function length(Bytes32Set storage set) internal view returns (uint256) {
                                    return _length(set._inner);
                                }
                               /**
                                * @dev Returns the value stored at position `index` in the set. O(1).
                                *
                                * Note that there are no guarantees on the ordering of values inside the
                                * array, and it may change when more values are added or removed.
                                *
                                * Requirements:
                                *
                                * - `index` must be strictly less than {length}.
                                */
                                function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                                    return _at(set._inner, index);
                                }
                                // AddressSet
                                struct AddressSet {
                                    Set _inner;
                                }
                                /**
                                 * @dev Add a value to a set. O(1).
                                 *
                                 * Returns true if the value was added to the set, that is if it was not
                                 * already present.
                                 */
                                function add(AddressSet storage set, address value) internal returns (bool) {
                                    return _add(set._inner, bytes32(uint256(value)));
                                }
                                /**
                                 * @dev Removes a value from a set. O(1).
                                 *
                                 * Returns true if the value was removed from the set, that is if it was
                                 * present.
                                 */
                                function remove(AddressSet storage set, address value) internal returns (bool) {
                                    return _remove(set._inner, bytes32(uint256(value)));
                                }
                                /**
                                 * @dev Returns true if the value is in the set. O(1).
                                 */
                                function contains(AddressSet storage set, address value) internal view returns (bool) {
                                    return _contains(set._inner, bytes32(uint256(value)));
                                }
                                /**
                                 * @dev Returns the number of values in the set. O(1).
                                 */
                                function length(AddressSet storage set) internal view returns (uint256) {
                                    return _length(set._inner);
                                }
                               /**
                                * @dev Returns the value stored at position `index` in the set. O(1).
                                *
                                * Note that there are no guarantees on the ordering of values inside the
                                * array, and it may change when more values are added or removed.
                                *
                                * Requirements:
                                *
                                * - `index` must be strictly less than {length}.
                                */
                                function at(AddressSet storage set, uint256 index) internal view returns (address) {
                                    return address(uint256(_at(set._inner, index)));
                                }
                                // UintSet
                                struct UintSet {
                                    Set _inner;
                                }
                                /**
                                 * @dev Add a value to a set. O(1).
                                 *
                                 * Returns true if the value was added to the set, that is if it was not
                                 * already present.
                                 */
                                function add(UintSet storage set, uint256 value) internal returns (bool) {
                                    return _add(set._inner, bytes32(value));
                                }
                                /**
                                 * @dev Removes a value from a set. O(1).
                                 *
                                 * Returns true if the value was removed from the set, that is if it was
                                 * present.
                                 */
                                function remove(UintSet storage set, uint256 value) internal returns (bool) {
                                    return _remove(set._inner, bytes32(value));
                                }
                                /**
                                 * @dev Returns true if the value is in the set. O(1).
                                 */
                                function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                                    return _contains(set._inner, bytes32(value));
                                }
                                /**
                                 * @dev Returns the number of values on the set. O(1).
                                 */
                                function length(UintSet storage set) internal view returns (uint256) {
                                    return _length(set._inner);
                                }
                               /**
                                * @dev Returns the value stored at position `index` in the set. O(1).
                                *
                                * Note that there are no guarantees on the ordering of values inside the
                                * array, and it may change when more values are added or removed.
                                *
                                * Requirements:
                                *
                                * - `index` must be strictly less than {length}.
                                */
                                function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                                    return uint256(_at(set._inner, index));
                                }
                            }
                            // File: openzeppelin-solidity/contracts/utils/Address.sol
                            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: openzeppelin-solidity/contracts/GSN/Context.sol
                            pragma solidity >=0.6.0 <0.8.0;
                            /*
                             * @dev Provides information about the current execution context, including the
                             * sender of the transaction and its data. While these are generally available
                             * via msg.sender and msg.data, they should not be accessed in such a direct
                             * manner, since when dealing with GSN meta-transactions the account sending and
                             * paying for execution may not be the actual sender (as far as an application
                             * is concerned).
                             *
                             * This contract is only required for intermediate, library-like contracts.
                             */
                            abstract contract Context {
                                function _msgSender() internal view virtual returns (address payable) {
                                    return msg.sender;
                                }
                                function _msgData() internal view virtual returns (bytes memory) {
                                    this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                                    return msg.data;
                                }
                            }
                            // File: openzeppelin-solidity/contracts/access/AccessControl.sol
                            pragma solidity >=0.6.0 <0.8.0;
                            /**
                             * @dev Contract module that allows children to implement role-based access
                             * control mechanisms.
                             *
                             * Roles are referred to by their `bytes32` identifier. These should be exposed
                             * in the external API and be unique. The best way to achieve this is by
                             * using `public constant` hash digests:
                             *
                             * ```
                             * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
                             * ```
                             *
                             * Roles can be used to represent a set of permissions. To restrict access to a
                             * function call, use {hasRole}:
                             *
                             * ```
                             * function foo() public {
                             *     require(hasRole(MY_ROLE, msg.sender));
                             *     ...
                             * }
                             * ```
                             *
                             * Roles can be granted and revoked dynamically via the {grantRole} and
                             * {revokeRole} functions. Each role has an associated admin role, and only
                             * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
                             *
                             * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
                             * that only accounts with this role will be able to grant or revoke other
                             * roles. More complex role relationships can be created by using
                             * {_setRoleAdmin}.
                             *
                             * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
                             * grant and revoke this role. Extra precautions should be taken to secure
                             * accounts that have been granted it.
                             */
                            abstract contract AccessControl is Context {
                                using EnumerableSet for EnumerableSet.AddressSet;
                                using Address for address;
                                struct RoleData {
                                    EnumerableSet.AddressSet members;
                                    bytes32 adminRole;
                                }
                                mapping (bytes32 => RoleData) private _roles;
                                bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
                                /**
                                 * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
                                 *
                                 * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
                                 * {RoleAdminChanged} not being emitted signaling this.
                                 *
                                 * _Available since v3.1._
                                 */
                                event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
                                /**
                                 * @dev Emitted when `account` is granted `role`.
                                 *
                                 * `sender` is the account that originated the contract call, an admin role
                                 * bearer except when using {_setupRole}.
                                 */
                                event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
                                /**
                                 * @dev Emitted when `account` is revoked `role`.
                                 *
                                 * `sender` is the account that originated the contract call:
                                 *   - if using `revokeRole`, it is the admin role bearer
                                 *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
                                 */
                                event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
                                /**
                                 * @dev Returns `true` if `account` has been granted `role`.
                                 */
                                function hasRole(bytes32 role, address account) public view returns (bool) {
                                    return _roles[role].members.contains(account);
                                }
                                /**
                                 * @dev Returns the number of accounts that have `role`. Can be used
                                 * together with {getRoleMember} to enumerate all bearers of a role.
                                 */
                                function getRoleMemberCount(bytes32 role) public view returns (uint256) {
                                    return _roles[role].members.length();
                                }
                                /**
                                 * @dev Returns one of the accounts that have `role`. `index` must be a
                                 * value between 0 and {getRoleMemberCount}, non-inclusive.
                                 *
                                 * Role bearers are not sorted in any particular way, and their ordering may
                                 * change at any point.
                                 *
                                 * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
                                 * you perform all queries on the same block. See the following
                                 * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
                                 * for more information.
                                 */
                                function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
                                    return _roles[role].members.at(index);
                                }
                                /**
                                 * @dev Returns the admin role that controls `role`. See {grantRole} and
                                 * {revokeRole}.
                                 *
                                 * To change a role's admin, use {_setRoleAdmin}.
                                 */
                                function getRoleAdmin(bytes32 role) public view returns (bytes32) {
                                    return _roles[role].adminRole;
                                }
                                /**
                                 * @dev Grants `role` to `account`.
                                 *
                                 * If `account` had not been already granted `role`, emits a {RoleGranted}
                                 * event.
                                 *
                                 * Requirements:
                                 *
                                 * - the caller must have ``role``'s admin role.
                                 */
                                function grantRole(bytes32 role, address account) public virtual {
                                    require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
                                    _grantRole(role, account);
                                }
                                /**
                                 * @dev Revokes `role` from `account`.
                                 *
                                 * If `account` had been granted `role`, emits a {RoleRevoked} event.
                                 *
                                 * Requirements:
                                 *
                                 * - the caller must have ``role``'s admin role.
                                 */
                                function revokeRole(bytes32 role, address account) public virtual {
                                    require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
                                    _revokeRole(role, account);
                                }
                                /**
                                 * @dev Revokes `role` from the calling account.
                                 *
                                 * Roles are often managed via {grantRole} and {revokeRole}: this function's
                                 * purpose is to provide a mechanism for accounts to lose their privileges
                                 * if they are compromised (such as when a trusted device is misplaced).
                                 *
                                 * If the calling account had been granted `role`, emits a {RoleRevoked}
                                 * event.
                                 *
                                 * Requirements:
                                 *
                                 * - the caller must be `account`.
                                 */
                                function renounceRole(bytes32 role, address account) public virtual {
                                    require(account == _msgSender(), "AccessControl: can only renounce roles for self");
                                    _revokeRole(role, account);
                                }
                                /**
                                 * @dev Grants `role` to `account`.
                                 *
                                 * If `account` had not been already granted `role`, emits a {RoleGranted}
                                 * event. Note that unlike {grantRole}, this function doesn't perform any
                                 * checks on the calling account.
                                 *
                                 * [WARNING]
                                 * ====
                                 * This function should only be called from the constructor when setting
                                 * up the initial roles for the system.
                                 *
                                 * Using this function in any other way is effectively circumventing the admin
                                 * system imposed by {AccessControl}.
                                 * ====
                                 */
                                function _setupRole(bytes32 role, address account) internal virtual {
                                    _grantRole(role, account);
                                }
                                /**
                                 * @dev Sets `adminRole` as ``role``'s admin role.
                                 *
                                 * Emits a {RoleAdminChanged} event.
                                 */
                                function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
                                    emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
                                    _roles[role].adminRole = adminRole;
                                }
                                function _grantRole(bytes32 role, address account) private {
                                    if (_roles[role].members.add(account)) {
                                        emit RoleGranted(role, account, _msgSender());
                                    }
                                }
                                function _revokeRole(bytes32 role, address account) private {
                                    if (_roles[role].members.remove(account)) {
                                        emit RoleRevoked(role, account, _msgSender());
                                    }
                                }
                            }
                            // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
                            pragma solidity >=0.6.0 <0.8.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: openzeppelin-solidity/contracts/math/SafeMath.sol
                            pragma solidity >=0.6.0 <0.8.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-solidity/contracts/token/ERC20/SafeERC20.sol
                            pragma solidity >=0.6.0 <0.8.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: original_contracts/routers/IRouter.sol
                            pragma solidity 0.7.5;
                            interface IRouter {
                                /**
                                * @dev Certain routers/exchanges needs to be initialized.
                                * This method will be called from Augustus
                                */
                                function initialize(bytes calldata data) external;
                                /**
                                * @dev Returns unique identifier for the router
                                */
                                function getKey() external pure returns(bytes32);
                                event Swapped(
                                    bytes16 uuid,
                                    address initiator,
                                    address indexed beneficiary,
                                    address indexed srcToken,
                                    address indexed destToken,
                                    uint256 srcAmount,
                                    uint256 receivedAmount,
                                    uint256 expectedAmount
                                );
                                event Bought(
                                    bytes16 uuid,
                                    address initiator,
                                    address indexed beneficiary,
                                    address indexed srcToken,
                                    address indexed destToken,
                                    uint256 srcAmount,
                                    uint256 receivedAmount
                                );
                                event FeeTaken(
                                    uint256 fee,
                                    uint256 partnerShare,
                                    uint256 paraswapShare
                                );
                            }
                            // File: original_contracts/ITokenTransferProxy.sol
                            pragma solidity 0.7.5;
                            interface ITokenTransferProxy {
                                function transferFrom(
                                    address token,
                                    address from,
                                    address to,
                                    uint256 amount
                                )
                                    external;
                            }
                            // File: original_contracts/lib/Utils.sol
                            pragma solidity 0.7.5;
                            pragma experimental ABIEncoderV2;
                            interface IERC20Permit {
                                function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
                            }
                            library Utils {
                                using SafeMath for uint256;
                                using SafeERC20 for IERC20;
                                address constant ETH_ADDRESS = address(
                                    0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
                                );
                                
                                uint256 constant MAX_UINT = type(uint256).max;
                                /**
                               * @param fromToken Address of the source token
                               * @param fromAmount Amount of source tokens to be swapped
                               * @param toAmount Minimum destination token amount expected out of this swap
                               * @param expectedAmount Expected amount of destination tokens without slippage
                               * @param beneficiary Beneficiary address
                               * 0 then 100% will be transferred to beneficiary. Pass 10000 for 100%
                               * @param path Route to be taken for this swap to take place
                               */
                                struct SellData {
                                    address fromToken;
                                    uint256 fromAmount;
                                    uint256 toAmount;
                                    uint256 expectedAmount;
                                    address payable beneficiary;
                                    Utils.Path[] path;
                                    address payable partner;
                                    uint256 feePercent;
                                    bytes permit;
                                    uint256 deadline;
                                    bytes16 uuid;
                                }
                                struct MegaSwapSellData {
                                    address fromToken;
                                    uint256 fromAmount;
                                    uint256 toAmount;
                                    uint256 expectedAmount;
                                    address payable beneficiary;
                                    Utils.MegaSwapPath[] path;
                                    address payable partner;
                                    uint256 feePercent;
                                    bytes permit;
                                    uint256 deadline;
                                    bytes16 uuid;
                                }
                                struct SimpleData {
                                    address fromToken;
                                    address toToken;
                                    uint256 fromAmount;
                                    uint256 toAmount;
                                    uint256 expectedAmount;
                                    address[] callees;
                                    bytes exchangeData;
                                    uint256[] startIndexes;
                                    uint256[] values;
                                    address payable beneficiary;
                                    address payable partner;
                                    uint256 feePercent;
                                    bytes permit;
                                    uint256 deadline;
                                    bytes16 uuid;
                                }
                                struct Adapter {
                                    address payable adapter;
                                    uint256 percent;
                                    uint256 networkFee;
                                    Route[] route;
                                }
                                struct Route {
                                    uint256 index;//Adapter at which index needs to be used
                                    address targetExchange;
                                    uint percent;
                                    bytes payload;
                                    uint256 networkFee;//Network fee is associated with 0xv3 trades
                                }
                                struct MegaSwapPath {
                                    uint256 fromAmountPercent;
                                    Path[] path;
                                }
                                struct Path {
                                    address to;
                                    uint256 totalNetworkFee;//Network fee is associated with 0xv3 trades
                                    Adapter[] adapters;
                                }
                                function ethAddress() internal pure returns (address) {return ETH_ADDRESS;}
                                function maxUint() internal pure returns (uint256) {return MAX_UINT;}
                                function approve(
                                    address addressToApprove,
                                    address token,
                                    uint256 amount
                                ) internal {
                                    if (token != ETH_ADDRESS) {
                                        IERC20 _token = IERC20(token);
                                        uint allowance = _token.allowance(address(this), addressToApprove);
                                        if (allowance < amount) {
                                            _token.safeApprove(addressToApprove, 0);
                                            _token.safeIncreaseAllowance(addressToApprove, MAX_UINT);
                                        }
                                    }
                                }
                                function transferTokens(
                                    address token,
                                    address payable destination,
                                    uint256 amount
                                )
                                internal
                                {
                                    if (amount > 0) {
                                        if (token == ETH_ADDRESS) {
                                            (bool result, ) = destination.call{value: amount, gas: 10000}("");
                                            require(result, "Failed to transfer Ether");
                                        }
                                        else {
                                            IERC20(token).safeTransfer(destination, amount);
                                        }
                                    }
                                }
                                function tokenBalance(
                                    address token,
                                    address account
                                )
                                internal
                                view
                                returns (uint256)
                                {
                                    if (token == ETH_ADDRESS) {
                                        return account.balance;
                                    } else {
                                        return IERC20(token).balanceOf(account);
                                    }
                                }
                                function permit(
                                    address token,
                                    bytes memory permit
                                )
                                    internal
                                {
                                    if (permit.length == 32 * 7) {
                                        (bool success,) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit));
                                        require(success, "Permit failed");
                                    }
                                }
                            }
                            // File: original_contracts/adapters/IAdapter.sol
                            pragma solidity 0.7.5;
                            interface IAdapter {
                                /**
                                * @dev Certain adapters needs to be initialized.
                                * This method will be called from Augustus
                                */
                                function initialize(bytes calldata data) external;
                                /**
                               * @dev The function which performs the swap on an exchange.
                               * @param fromToken Address of the source token
                               * @param toToken Address of the destination token
                               * @param fromAmount Amount of source tokens to be swapped
                               * @param networkFee Network fee to be used in this router
                               * @param route Route to be followed
                               */
                                function swap(
                                    IERC20 fromToken,
                                    IERC20 toToken,
                                    uint256 fromAmount,
                                    uint256 networkFee,
                                    Utils.Route[] calldata route
                                )
                                    external
                                    payable;
                            }
                            // File: openzeppelin-solidity/contracts/access/Ownable.sol
                            pragma solidity >=0.6.0 <0.8.0;
                            /**
                             * @dev Contract module which provides a basic access control mechanism, where
                             * there is an account (an owner) that can be granted exclusive access to
                             * specific functions.
                             *
                             * By default, the owner account will be the one that deploys the contract. This
                             * can later be changed with {transferOwnership}.
                             *
                             * This module is used through inheritance. It will make available the modifier
                             * `onlyOwner`, which can be applied to your functions to restrict their use to
                             * the owner.
                             */
                            abstract contract Ownable is Context {
                                address private _owner;
                                event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                                /**
                                 * @dev Initializes the contract setting the deployer as the initial owner.
                                 */
                                constructor () internal {
                                    address msgSender = _msgSender();
                                    _owner = msgSender;
                                    emit OwnershipTransferred(address(0), msgSender);
                                }
                                /**
                                 * @dev Returns the address of the current owner.
                                 */
                                function owner() public view returns (address) {
                                    return _owner;
                                }
                                /**
                                 * @dev Throws if called by any account other than the owner.
                                 */
                                modifier onlyOwner() {
                                    require(_owner == _msgSender(), "Ownable: caller is not the owner");
                                    _;
                                }
                                /**
                                 * @dev Leaves the contract without owner. It will not be possible to call
                                 * `onlyOwner` functions anymore. Can only be called by the current owner.
                                 *
                                 * NOTE: Renouncing ownership will leave the contract without an owner,
                                 * thereby removing any functionality that is only available to the owner.
                                 */
                                function renounceOwnership() public virtual onlyOwner {
                                    emit OwnershipTransferred(_owner, address(0));
                                    _owner = address(0);
                                }
                                /**
                                 * @dev Transfers ownership of the contract to a new account (`newOwner`).
                                 * Can only be called by the current owner.
                                 */
                                function transferOwnership(address newOwner) public virtual onlyOwner {
                                    require(newOwner != address(0), "Ownable: new owner is the zero address");
                                    emit OwnershipTransferred(_owner, newOwner);
                                    _owner = newOwner;
                                }
                            }
                            // File: original_contracts/TokenTransferProxy.sol
                            pragma solidity 0.7.5;
                            /**
                            * @dev Allows owner of the contract to transfer tokens on behalf of user.
                            * User will need to approve this contract to spend tokens on his/her behalf
                            * on Paraswap platform
                            */
                            contract TokenTransferProxy is Ownable, ITokenTransferProxy {
                                using SafeERC20 for IERC20;
                                using Address for address;
                                /**
                                * @dev Allows owner of the contract to transfer tokens on user's behalf
                                * @dev Swapper contract will be the owner of this contract
                                * @param token Address of the token
                                * @param from Address from which tokens will be transferred
                                * @param to Receipent address of the tokens
                                * @param amount Amount of tokens to transfer
                                */
                                function transferFrom(
                                    address token,
                                    address from,
                                    address to,
                                    uint256 amount
                                )
                                    external
                                    override
                                    onlyOwner
                                {   
                                    require(
                                        from == tx.origin ||
                                        from.isContract(),
                                        "Invalid from address"
                                    );
                                    
                                    IERC20(token).safeTransferFrom(from, to, amount);
                                }
                            }
                            // File: original_contracts/AugustusStorage.sol
                            pragma solidity 0.7.5;
                            contract AugustusStorage {
                                struct FeeStructure {
                                    uint256 partnerShare;
                                    bool noPositiveSlippage;
                                    bool positiveSlippageToUser;
                                    uint16 feePercent;
                                    string partnerId;
                                    bytes data;
                                }
                                ITokenTransferProxy internal tokenTransferProxy;
                                address payable internal feeWallet;
                                
                                mapping(address => FeeStructure) internal registeredPartners;
                                mapping (bytes4 => address) internal selectorVsRouter;
                                mapping (bytes32 => bool) internal adapterInitialized;
                                mapping (bytes32 => bytes) internal adapterVsData;
                                mapping (bytes32 => bytes) internal routerData;
                                mapping (bytes32 => bool) internal routerInitialized;
                                bytes32 public constant WHITELISTED_ROLE = keccak256("WHITELISTED_ROLE");
                                bytes32 public constant ROUTER_ROLE = keccak256("ROUTER_ROLE");
                            }
                            // File: original_contracts/AugustusSwapper.sol
                            pragma solidity 0.7.5;
                            contract AugustusSwapper is AugustusStorage, AccessControl {
                                using SafeMath for uint256;
                                using SafeERC20 for IERC20;
                                event AdapterInitialized(address indexed adapter);
                                event RouterInitialized(address indexed router);
                                /**
                                 * @dev Throws if called by any account other than the admin.
                                 */
                                modifier onlyAdmin() {
                                    require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "caller is not the admin");
                                    _;
                                }
                                constructor(address payable _feeWallet) public {
                                    TokenTransferProxy lTokenTransferProxy = new TokenTransferProxy();
                                    tokenTransferProxy = ITokenTransferProxy(lTokenTransferProxy);
                                    feeWallet = _feeWallet;
                                    _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
                                }
                                
                                receive () payable external {
                                }
                                fallback() external payable {
                                    bytes4 selector = msg.sig;
                                    //Figure out the router contract for the given function
                                    address implementation = getImplementation(selector);
                                    if (implementation == address(0)) {
                                        _revertWithData(
                                            abi.encodeWithSelector(
                                                bytes4(keccak256("NotImplementedError(bytes4)")),
                                                selector
                                            )
                                        );
                                    }
                                    //Delegate call to the router
                                    (bool success, bytes memory resultData) = implementation.delegatecall(msg.data);
                                    if (!success) {
                                        _revertWithData(resultData);
                                    }
                                    _returnWithData(resultData);
                                }
                                function initializeAdapter(address adapter, bytes calldata data) external onlyAdmin {
                                    require(
                                        hasRole(WHITELISTED_ROLE, adapter),
                                        "Exchange not whitelisted"
                                    );
                                    (bool success,) = adapter.delegatecall(abi.encodeWithSelector(IAdapter.initialize.selector, data));
                                    require(success, "Failed to initialize adapter");
                                    emit AdapterInitialized(adapter);
                                }
                                function initializeRouter(address router, bytes calldata data) external onlyAdmin {
                                    require(
                                        hasRole(ROUTER_ROLE, router),
                                        "Router not whitelisted"
                                    );
                                    (bool success,) = router.delegatecall(abi.encodeWithSelector(IRouter.initialize.selector, data));
                                    require(success, "Failed to initialize router");
                                    emit RouterInitialized(router);
                                } 
                                
                                function getImplementation(bytes4 selector) public view returns(address) {
                                    return selectorVsRouter[selector];
                                }
                                function getVersion() external pure returns(string memory) {
                                    return "5.0.0";
                                }
                                function getPartnerFeeStructure(address partner) public view returns (FeeStructure memory) {
                                    return registeredPartners[partner];
                                }
                                function getFeeWallet() external view returns(address) {
                                    return feeWallet;
                                }
                                function setFeeWallet(address payable _feeWallet) external onlyAdmin {
                                    require(_feeWallet != address(0), "Invalid address");
                                    feeWallet = _feeWallet;
                                }
                                function registerPartner(
                                    address partner,
                                    uint256 _partnerShare,
                                    bool _noPositiveSlippage,
                                    bool _positiveSlippageToUser,
                                    uint16 _feePercent,
                                    string calldata partnerId,
                                    bytes calldata _data
                                )
                                    external
                                    onlyAdmin
                                {   
                                    require(partner != address(0), "Invalid partner");
                                    FeeStructure storage feeStructure = registeredPartners[partner];
                                    require(feeStructure.partnerShare == 0, "Already registered");
                                    require(_partnerShare > 0 && _partnerShare < 10000, "Invalid values");
                                    require(_feePercent <= 10000, "Invalid values");
                                    feeStructure.partnerShare = _partnerShare;
                                    feeStructure.noPositiveSlippage = _noPositiveSlippage;
                                    feeStructure.positiveSlippageToUser = _positiveSlippageToUser;
                                    feeStructure.partnerId = partnerId;
                                    feeStructure.feePercent = _feePercent;
                                    feeStructure.data = _data;
                                }
                                function setImplementation(bytes4 selector, address implementation) external onlyAdmin {
                                    require(
                                        hasRole(ROUTER_ROLE, implementation),
                                        "Router is not whitelisted"
                                    );
                                    selectorVsRouter[selector] = implementation;
                                }
                                /**
                                * @dev Allows admin of the contract to transfer any tokens which are assigned to the contract
                                * This method is for safety if by any chance tokens or ETHs are assigned to the contract by mistake
                                * @dev token Address of the token to be transferred
                                * @dev destination Recepient of the token
                                * @dev amount Amount of tokens to be transferred
                                */
                                function transferTokens(
                                    address token,
                                    address payable destination,
                                    uint256 amount
                                )
                                    external
                                    onlyAdmin
                                {
                                    if (amount > 0) {
                                        if (token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) {
                                            (bool result, ) = destination.call{value: amount, gas: 10000}("");
                                            require(result, "Failed to transfer Ether");
                                        }
                                        else {
                                            IERC20(token).safeTransfer(destination, amount);
                                        }
                                    }
                                }
                                  function isAdapterInitialized(bytes32 key) public view returns(bool) {
                                    return adapterInitialized[key];
                                }
                                function getAdapterData(bytes32 key) public view returns(bytes memory) {
                                    return adapterVsData[key];
                                }
                                function isRouterInitialized(bytes32 key) public view returns (bool) {
                                    return routerInitialized[key];
                                }
                                function getRouterData(bytes32 key) public view returns (bytes memory) {
                                    return routerData[key];
                                }
                                function getTokenTransferProxy() public view returns (address) {
                                    return address(tokenTransferProxy);
                                }
                                function _revertWithData(bytes memory data) private pure {
                                    assembly { revert(add(data, 32), mload(data)) }
                                }
                                function _returnWithData(bytes memory data) private pure {
                                    assembly { return(add(data, 32), mload(data)) }
                                }
                            }
                            

                            File 2 of 12: AppProxyUpgradeable
                            // File: contracts/common/UnstructuredStorage.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            library UnstructuredStorage {
                                function getStorageBool(bytes32 position) internal view returns (bool data) {
                                    assembly { data := sload(position) }
                                }
                            
                                function getStorageAddress(bytes32 position) internal view returns (address data) {
                                    assembly { data := sload(position) }
                                }
                            
                                function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
                                    assembly { data := sload(position) }
                                }
                            
                                function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
                                    assembly { data := sload(position) }
                                }
                            
                                function setStorageBool(bytes32 position, bool data) internal {
                                    assembly { sstore(position, data) }
                                }
                            
                                function setStorageAddress(bytes32 position, address data) internal {
                                    assembly { sstore(position, data) }
                                }
                            
                                function setStorageBytes32(bytes32 position, bytes32 data) internal {
                                    assembly { sstore(position, data) }
                                }
                            
                                function setStorageUint256(bytes32 position, uint256 data) internal {
                                    assembly { sstore(position, data) }
                                }
                            }
                            
                            // File: contracts/acl/IACL.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            interface IACL {
                                function initialize(address permissionsCreator) external;
                            
                                // TODO: this should be external
                                // See https://github.com/ethereum/solidity/issues/4832
                                function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                            }
                            
                            // File: contracts/common/IVaultRecoverable.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            interface IVaultRecoverable {
                                event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
                            
                                function transferToVault(address token) external;
                            
                                function allowRecoverability(address token) external view returns (bool);
                                function getRecoveryVault() external view returns (address);
                            }
                            
                            // File: contracts/kernel/IKernel.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            
                            interface IKernelEvents {
                                event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
                            }
                            
                            
                            // This should be an interface, but interfaces can't inherit yet :(
                            contract IKernel is IKernelEvents, IVaultRecoverable {
                                function acl() public view returns (IACL);
                                function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                            
                                function setApp(bytes32 namespace, bytes32 appId, address app) public;
                                function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
                            }
                            
                            // File: contracts/apps/AppStorage.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            
                            contract AppStorage {
                                using UnstructuredStorage for bytes32;
                            
                                /* Hardcoded constants to save gas
                                bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
                                bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
                                */
                                bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
                                bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
                            
                                function kernel() public view returns (IKernel) {
                                    return IKernel(KERNEL_POSITION.getStorageAddress());
                                }
                            
                                function appId() public view returns (bytes32) {
                                    return APP_ID_POSITION.getStorageBytes32();
                                }
                            
                                function setKernel(IKernel _kernel) internal {
                                    KERNEL_POSITION.setStorageAddress(address(_kernel));
                                }
                            
                                function setAppId(bytes32 _appId) internal {
                                    APP_ID_POSITION.setStorageBytes32(_appId);
                                }
                            }
                            
                            // File: contracts/common/IsContract.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            contract IsContract {
                                /*
                                * NOTE: this should NEVER be used for authentication
                                * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
                                *
                                * This is only intended to be used as a sanity check that an address is actually a contract,
                                * RATHER THAN an address not being a contract.
                                */
                                function isContract(address _target) internal view returns (bool) {
                                    if (_target == address(0)) {
                                        return false;
                                    }
                            
                                    uint256 size;
                                    assembly { size := extcodesize(_target) }
                                    return size > 0;
                                }
                            }
                            
                            // File: contracts/lib/misc/ERCProxy.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            contract ERCProxy {
                                uint256 internal constant FORWARDING = 1;
                                uint256 internal constant UPGRADEABLE = 2;
                            
                                function proxyType() public pure returns (uint256 proxyTypeId);
                                function implementation() public view returns (address codeAddr);
                            }
                            
                            // File: contracts/common/DelegateProxy.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            contract DelegateProxy is ERCProxy, IsContract {
                                uint256 internal constant FWD_GAS_LIMIT = 10000;
                            
                                /**
                                * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!)
                                * @param _dst Destination address to perform the delegatecall
                                * @param _calldata Calldata for the delegatecall
                                */
                                function delegatedFwd(address _dst, bytes _calldata) internal {
                                    require(isContract(_dst));
                                    uint256 fwdGasLimit = FWD_GAS_LIMIT;
                            
                                    assembly {
                                        let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
                                        let size := returndatasize
                                        let ptr := mload(0x40)
                                        returndatacopy(ptr, 0, size)
                            
                                        // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
                                        // if the call returned error data, forward it
                                        switch result case 0 { revert(ptr, size) }
                                        default { return(ptr, size) }
                                    }
                                }
                            }
                            
                            // File: contracts/common/DepositableStorage.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            contract DepositableStorage {
                                using UnstructuredStorage for bytes32;
                            
                                // keccak256("aragonOS.depositableStorage.depositable")
                                bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea;
                            
                                function isDepositable() public view returns (bool) {
                                    return DEPOSITABLE_POSITION.getStorageBool();
                                }
                            
                                function setDepositable(bool _depositable) internal {
                                    DEPOSITABLE_POSITION.setStorageBool(_depositable);
                                }
                            }
                            
                            // File: contracts/common/DepositableDelegateProxy.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            contract DepositableDelegateProxy is DepositableStorage, DelegateProxy {
                                event ProxyDeposit(address sender, uint256 value);
                            
                                function () external payable {
                                    uint256 forwardGasThreshold = FWD_GAS_LIMIT;
                                    bytes32 isDepositablePosition = DEPOSITABLE_POSITION;
                            
                                    // Optimized assembly implementation to prevent EIP-1884 from breaking deposits, reference code in Solidity:
                                    // https://github.com/aragon/aragonOS/blob/v4.2.1/contracts/common/DepositableDelegateProxy.sol#L10-L20
                                    assembly {
                                        // Continue only if the gas left is lower than the threshold for forwarding to the implementation code,
                                        // otherwise continue outside of the assembly block.
                                        if lt(gas, forwardGasThreshold) {
                                            // Only accept the deposit and emit an event if all of the following are true:
                                            // the proxy accepts deposits (isDepositable), msg.data.length == 0, and msg.value > 0
                                            if and(and(sload(isDepositablePosition), iszero(calldatasize)), gt(callvalue, 0)) {
                                                // Equivalent Solidity code for emitting the event:
                                                // emit ProxyDeposit(msg.sender, msg.value);
                            
                                                let logData := mload(0x40) // free memory pointer
                                                mstore(logData, caller) // add 'msg.sender' to the log data (first event param)
                                                mstore(add(logData, 0x20), callvalue) // add 'msg.value' to the log data (second event param)
                            
                                                // Emit an event with one topic to identify the event: keccak256('ProxyDeposit(address,uint256)') = 0x15ee...dee1
                                                log1(logData, 0x40, 0x15eeaa57c7bd188c1388020bcadc2c436ec60d647d36ef5b9eb3c742217ddee1)
                            
                                                stop() // Stop. Exits execution context
                                            }
                            
                                            // If any of above checks failed, revert the execution (if ETH was sent, it is returned to the sender)
                                            revert(0, 0)
                                        }
                                    }
                            
                                    address target = implementation();
                                    delegatedFwd(target, msg.data);
                                }
                            }
                            
                            // File: contracts/kernel/KernelConstants.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            contract KernelAppIds {
                                /* Hardcoded constants to save gas
                                bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
                                bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
                                bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
                                */
                                bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
                                bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
                                bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
                            }
                            
                            
                            contract KernelNamespaceConstants {
                                /* Hardcoded constants to save gas
                                bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
                                bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
                                bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
                                */
                                bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
                                bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
                                bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
                            }
                            
                            // File: contracts/apps/AppProxyBase.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            
                            
                            contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants {
                                /**
                                * @dev Initialize AppProxy
                                * @param _kernel Reference to organization kernel for the app
                                * @param _appId Identifier for app
                                * @param _initializePayload Payload for call to be made after setup to initialize
                                */
                                constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public {
                                    setKernel(_kernel);
                                    setAppId(_appId);
                            
                                    // Implicit check that kernel is actually a Kernel
                                    // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to
                                    // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on
                                    // it.
                                    address appCode = getAppBase(_appId);
                            
                                    // If initialize payload is provided, it will be executed
                                    if (_initializePayload.length > 0) {
                                        require(isContract(appCode));
                                        // Cannot make delegatecall as a delegateproxy.delegatedFwd as it
                                        // returns ending execution context and halts contract deployment
                                        require(appCode.delegatecall(_initializePayload));
                                    }
                                }
                            
                                function getAppBase(bytes32 _appId) internal view returns (address) {
                                    return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId);
                                }
                            }
                            
                            // File: contracts/apps/AppProxyUpgradeable.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            contract AppProxyUpgradeable is AppProxyBase {
                                /**
                                * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app)
                                * @param _kernel Reference to organization kernel for the app
                                * @param _appId Identifier for app
                                * @param _initializePayload Payload for call to be made after setup to initialize
                                */
                                constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
                                    AppProxyBase(_kernel, _appId, _initializePayload)
                                    public // solium-disable-line visibility-first
                                {
                                    // solium-disable-previous-line no-empty-blocks
                                }
                            
                                /**
                                 * @dev ERC897, the address the proxy would delegate calls to
                                 */
                                function implementation() public view returns (address) {
                                    return getAppBase(appId());
                                }
                            
                                /**
                                 * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
                                 */
                                function proxyType() public pure returns (uint256 proxyTypeId) {
                                    return UPGRADEABLE;
                                }
                            }

                            File 3 of 12: 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 4 of 12: NewUniswapV2ExchangeRouter
                            // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
                            pragma solidity >=0.6.0 <0.8.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: original_contracts/lib/weth/IWETH.sol
                            pragma solidity 0.7.5;
                            abstract contract IWETH is IERC20 {
                                function deposit() external virtual payable;
                                function withdraw(uint256 amount) external virtual;
                            }
                            // File: original_contracts/lib/uniswapv2/IUniswapV2Pair.sol
                            pragma solidity 0.7.5;
                            interface IUniswapV2Pair {
                                function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
                                function swap(
                                    uint amount0Out,
                                    uint amount1Out,
                                    address to,
                                    bytes calldata data
                                )
                                    external;
                            }
                            // File: openzeppelin-solidity/contracts/math/SafeMath.sol
                            pragma solidity >=0.6.0 <0.8.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: original_contracts/lib/uniswapv2/NewUniswapV2Lib.sol
                            pragma solidity 0.7.5;
                            library NewUniswapV2Lib {
                                using SafeMath for uint256;
                                function getReservesByPair(
                                    address pair,
                                    bool direction
                                )
                                    internal
                                    view
                                    returns (uint256 reserveIn, uint256 reserveOut)
                                {
                                    (uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(pair).getReserves();
                                    (reserveIn, reserveOut) = direction ? (reserve0, reserve1) : (reserve1, reserve0);
                                }
                                function getAmountOut(
                                    uint256 amountIn,
                                    address pair,
                                    bool direction,
                                    uint256 fee
                                )
                                    internal
                                    view
                                    returns (uint256 amountOut)
                                {
                                    require(amountIn > 0, "UniswapV2Lib: INSUFFICIENT_INPUT_AMOUNT");
                                    (uint256 reserveIn, uint256 reserveOut) = getReservesByPair(pair, direction);
                                    uint256 amountInWithFee = amountIn.mul(fee);
                                    uint256 numerator = amountInWithFee.mul(reserveOut);
                                    uint256 denominator = reserveIn.mul(10000).add(amountInWithFee);
                                    amountOut = uint256(numerator / denominator);
                                }
                                function getAmountIn(
                                    uint256 amountOut,
                                    address pair,
                                    bool direction,
                                    uint256 fee
                                )
                                    internal
                                    view
                                    returns (uint256 amountIn)
                                {
                                    require(amountOut > 0, "UniswapV2Lib: INSUFFICIENT_OUTPUT_AMOUNT");
                                    (uint256 reserveIn, uint256 reserveOut) = getReservesByPair(pair, direction);
                                    require(reserveOut > amountOut, "UniswapV2Lib: reserveOut should be greater than amountOut");
                                    uint256 numerator = reserveIn.mul(amountOut).mul(10000);
                                    uint256 denominator = reserveOut.sub(amountOut).mul(fee);
                                    amountIn = (numerator / denominator).add(1);
                                }
                            }
                            // File: @uniswap/lib/contracts/libraries/TransferHelper.sol
                            pragma solidity >=0.6.0;
                            // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
                            library TransferHelper {
                                function safeApprove(address token, address to, uint value) internal {
                                    // bytes4(keccak256(bytes('approve(address,uint256)')));
                                    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
                                    require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
                                }
                                function safeTransfer(address token, address to, uint value) internal {
                                    // bytes4(keccak256(bytes('transfer(address,uint256)')));
                                    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
                                    require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
                                }
                                function safeTransferFrom(address token, address from, address to, uint value) internal {
                                    // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
                                    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
                                    require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
                                }
                                function safeTransferETH(address to, uint value) internal {
                                    (bool success,) = to.call{value:value}(new bytes(0));
                                    require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
                                }
                            }
                            // File: original_contracts/lib/uniswapv2/NewUniswapV2ExchangeRouter.sol
                            pragma solidity 0.7.5;
                            contract NewUniswapV2ExchangeRouter {
                                using SafeMath for uint256;
                                address constant ETH_IDENTIFIER = address(
                                    0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
                                );
                                // Pool bits are 255-161: fee, 160: direction flag, 159-0: address
                                uint256 constant FEE_OFFSET = 161;
                                uint256 constant DIRECTION_FLAG =
                                    0x0000000000000000000000010000000000000000000000000000000000000000;
                                receive() external payable {
                                }
                                function swap(
                                    address tokenIn,
                                    uint256 amountIn,
                                    uint256 amountOutMin,
                                    address weth,
                                    uint256[] calldata pools
                                )
                                    external
                                    payable
                                    returns (uint256 tokensBought)
                                {
                                    return _swap(
                                        tokenIn,
                                        amountIn,
                                        amountOutMin,
                                        weth,
                                        pools
                                    );
                                }
                                function buy(
                                    address tokenIn,
                                    uint256 amountInMax,
                                    uint256 amountOut,
                                    address weth,
                                    uint256[] memory pools
                                )
                                    external
                                    payable
                                    returns (uint256 tokensSold)
                                {
                                    return _buy(
                                        tokenIn,
                                        amountInMax,
                                        amountOut,
                                        weth,
                                        pools
                                    );
                                }
                                function _swap(
                                    address tokenIn,
                                    uint256 amountIn,
                                    uint256 amountOutMin,
                                    address weth,
                                    uint256[] memory pools
                                )
                                    private
                                    returns (uint256 tokensBought)
                                {
                                    uint256 pairs = pools.length;
                                    require(pairs != 0, "At least one pool required");
                                    bool tokensBoughtEth;
                                    if (tokenIn == ETH_IDENTIFIER) {
                                        require(amountIn == msg.value, "Incorrect amount of ETH sent");
                                        IWETH(weth).deposit{value: msg.value}();
                                        require(IWETH(weth).transfer(address(pools[0]), msg.value));
                                    } else {
                                        TransferHelper.safeTransferFrom(
                                            tokenIn, msg.sender, address(pools[0]), amountIn
                                        );
                                        tokensBoughtEth = weth != address(0);
                                    }
                                    tokensBought = amountIn;
                                    for (uint256 i = 0; i < pairs; ++i) {
                                        uint256 p = pools[i];
                                        address pool = address(p);
                                        bool direction = p & DIRECTION_FLAG == 0;
                                        tokensBought = NewUniswapV2Lib.getAmountOut(
                                            tokensBought, pool, direction, p >> FEE_OFFSET
                                        );
                                        (uint256 amount0Out, uint256 amount1Out) = direction
                                            ? (uint256(0), tokensBought) : (tokensBought, uint256(0));
                                        IUniswapV2Pair(pool).swap(
                                            amount0Out,
                                            amount1Out,
                                            i + 1 == pairs
                                                ? (tokensBoughtEth ? address(this) : msg.sender)
                                                : address(pools[i + 1]),
                                            ""
                                        );
                                    }
                                    if (tokensBoughtEth) {
                                        IWETH(weth).withdraw(tokensBought);
                                        TransferHelper.safeTransferETH(msg.sender, tokensBought);
                                    }
                                    require(tokensBought >= amountOutMin, "UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT");
                                }
                                function _buy(
                                    address tokenIn,
                                    uint256 amountInMax,
                                    uint256 amountOut,
                                    address weth,
                                    uint256[] memory pools
                                )
                                    private
                                    returns (uint256 tokensSold)
                                {
                                    uint256 pairs = pools.length;
                                    require(pairs != 0, "At least one pool required");
                                    uint256[] memory amounts = new uint256[](pairs + 1);
                                    amounts[pairs] = amountOut;
                                    for (uint256 i = pairs; i != 0; --i) {
                                        uint256 p = pools[i - 1];
                                        amounts[i - 1] = NewUniswapV2Lib.getAmountIn(
                                            amounts[i],
                                            address(p),
                                            p & DIRECTION_FLAG == 0,
                                            p >> FEE_OFFSET
                                        );
                                    }
                                    tokensSold = amounts[0];
                                    require(tokensSold <= amountInMax, "UniswapV2Router: INSUFFICIENT_INPUT_AMOUNT");
                                    bool tokensBoughtEth;
                                    if (tokenIn == ETH_IDENTIFIER) {
                                        TransferHelper.safeTransferETH(
                                            msg.sender, msg.value.sub(tokensSold)
                                        );
                                        IWETH(weth).deposit{value: tokensSold}();
                                        require(IWETH(weth).transfer(address(pools[0]), tokensSold));
                                    } else {
                                        TransferHelper.safeTransferFrom(
                                            tokenIn, msg.sender, address(pools[0]), tokensSold
                                        );
                                        tokensBoughtEth = weth != address(0);
                                    }
                                    for (uint256 i = 0; i < pairs; ++i) {
                                        uint256 p = pools[i];
                                        (uint256 amount0Out, uint256 amount1Out) = p & DIRECTION_FLAG == 0
                                            ? (uint256(0), amounts[i + 1]) : (amounts[i + 1], uint256(0));
                                        IUniswapV2Pair(address(p)).swap(
                                            amount0Out,
                                            amount1Out,
                                            i + 1 == pairs
                                                ? (tokensBoughtEth ? address(this) : msg.sender)
                                                : address(pools[i + 1]),
                                            ""
                                        );
                                    }
                                    if (tokensBoughtEth) {
                                        IWETH(weth).withdraw(amountOut);
                                        TransferHelper.safeTransferETH(msg.sender, amountOut);
                                    }
                                }
                            }
                            

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

                            File 6 of 12: GnosisSafeProxy
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            
                            /// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
                            /// @author Richard Meissner - <[email protected]>
                            interface IProxy {
                                function masterCopy() external view returns (address);
                            }
                            
                            /// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
                            /// @author Stefan George - <[email protected]>
                            /// @author Richard Meissner - <[email protected]>
                            contract GnosisSafeProxy {
                                // singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
                                // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
                                address internal singleton;
                            
                                /// @dev Constructor function sets address of singleton contract.
                                /// @param _singleton Singleton address.
                                constructor(address _singleton) {
                                    require(_singleton != address(0), "Invalid singleton address provided");
                                    singleton = _singleton;
                                }
                            
                                /// @dev Fallback function forwards all transactions and returns all received return data.
                                fallback() external payable {
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
                                        // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
                                        if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
                                            mstore(0, _singleton)
                                            return(0, 0x20)
                                        }
                                        calldatacopy(0, 0, calldatasize())
                                        let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
                                        returndatacopy(0, 0, returndatasize())
                                        if eq(success, 0) {
                                            revert(0, returndatasize())
                                        }
                                        return(0, returndatasize())
                                    }
                                }
                            }
                            
                            /// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
                            /// @author Stefan George - <[email protected]>
                            contract GnosisSafeProxyFactory {
                                event ProxyCreation(GnosisSafeProxy proxy, address singleton);
                            
                                /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
                                /// @param singleton Address of singleton contract.
                                /// @param data Payload for message call sent to new proxy contract.
                                function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
                                    proxy = new GnosisSafeProxy(singleton);
                                    if (data.length > 0)
                                        // solhint-disable-next-line no-inline-assembly
                                        assembly {
                                            if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
                                                revert(0, 0)
                                            }
                                        }
                                    emit ProxyCreation(proxy, singleton);
                                }
                            
                                /// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
                                function proxyRuntimeCode() public pure returns (bytes memory) {
                                    return type(GnosisSafeProxy).runtimeCode;
                                }
                            
                                /// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
                                function proxyCreationCode() public pure returns (bytes memory) {
                                    return type(GnosisSafeProxy).creationCode;
                                }
                            
                                /// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
                                ///      This method is only meant as an utility to be called from other methods
                                /// @param _singleton Address of singleton contract.
                                /// @param initializer Payload for message call sent to new proxy contract.
                                /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                                function deployProxyWithNonce(
                                    address _singleton,
                                    bytes memory initializer,
                                    uint256 saltNonce
                                ) internal returns (GnosisSafeProxy proxy) {
                                    // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
                                    bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
                                    bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
                                    }
                                    require(address(proxy) != address(0), "Create2 call failed");
                                }
                            
                                /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
                                /// @param _singleton Address of singleton contract.
                                /// @param initializer Payload for message call sent to new proxy contract.
                                /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                                function createProxyWithNonce(
                                    address _singleton,
                                    bytes memory initializer,
                                    uint256 saltNonce
                                ) public returns (GnosisSafeProxy proxy) {
                                    proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
                                    if (initializer.length > 0)
                                        // solhint-disable-next-line no-inline-assembly
                                        assembly {
                                            if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
                                                revert(0, 0)
                                            }
                                        }
                                    emit ProxyCreation(proxy, _singleton);
                                }
                            
                                /// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
                                /// @param _singleton Address of singleton contract.
                                /// @param initializer Payload for message call sent to new proxy contract.
                                /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                                /// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
                                function createProxyWithCallback(
                                    address _singleton,
                                    bytes memory initializer,
                                    uint256 saltNonce,
                                    IProxyCreationCallback callback
                                ) public returns (GnosisSafeProxy proxy) {
                                    uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
                                    proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
                                    if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
                                }
                            
                                /// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
                                ///      This method is only meant for address calculation purpose when you use an initializer that would revert,
                                ///      therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
                                /// @param _singleton Address of singleton contract.
                                /// @param initializer Payload for message call sent to new proxy contract.
                                /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                                function calculateCreateProxyWithNonceAddress(
                                    address _singleton,
                                    bytes calldata initializer,
                                    uint256 saltNonce
                                ) external returns (GnosisSafeProxy proxy) {
                                    proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
                                    revert(string(abi.encodePacked(proxy)));
                                }
                            }
                            
                            interface IProxyCreationCallback {
                                function proxyCreated(
                                    GnosisSafeProxy proxy,
                                    address _singleton,
                                    bytes calldata initializer,
                                    uint256 saltNonce
                                ) external;
                            }

                            File 7 of 12: SimpleSwap
                            // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
                            pragma solidity >=0.6.0 <0.8.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: openzeppelin-solidity/contracts/math/SafeMath.sol
                            pragma solidity >=0.6.0 <0.8.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-solidity/contracts/utils/Address.sol
                            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: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
                            pragma solidity >=0.6.0 <0.8.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: original_contracts/ITokenTransferProxy.sol
                            pragma solidity 0.7.5;
                            interface ITokenTransferProxy {
                                function transferFrom(
                                    address token,
                                    address from,
                                    address to,
                                    uint256 amount
                                )
                                    external;
                            }
                            // File: original_contracts/lib/Utils.sol
                            pragma solidity 0.7.5;
                            pragma experimental ABIEncoderV2;
                            interface IERC20Permit {
                                function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
                            }
                            interface IERC20PermitLegacy {
                                function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;
                            }
                            library Utils {
                                using SafeMath for uint256;
                                using SafeERC20 for IERC20;
                                address constant ETH_ADDRESS = address(
                                    0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
                                );
                                
                                uint256 constant MAX_UINT = type(uint256).max;
                                /**
                               * @param fromToken Address of the source token
                               * @param fromAmount Amount of source tokens to be swapped
                               * @param toAmount Minimum destination token amount expected out of this swap
                               * @param expectedAmount Expected amount of destination tokens without slippage
                               * @param beneficiary Beneficiary address
                               * 0 then 100% will be transferred to beneficiary. Pass 10000 for 100%
                               * @param path Route to be taken for this swap to take place
                               */
                                struct SellData {
                                    address fromToken;
                                    uint256 fromAmount;
                                    uint256 toAmount;
                                    uint256 expectedAmount;
                                    address payable beneficiary;
                                    Utils.Path[] path;
                                    address payable partner;
                                    uint256 feePercent;
                                    bytes permit;
                                    uint256 deadline;
                                    bytes16 uuid;
                                }
                                struct BuyData {
                                    address adapter;
                                    address fromToken;
                                    address toToken;
                                    uint256 fromAmount;
                                    uint256 toAmount;
                                    address payable beneficiary;
                                    Utils.Route[] route;
                                    address payable partner;
                                    uint256 feePercent;
                                    bytes permit;
                                    uint256 deadline;
                                    bytes16 uuid;
                                }
                                struct MegaSwapSellData {
                                    address fromToken;
                                    uint256 fromAmount;
                                    uint256 toAmount;
                                    uint256 expectedAmount;
                                    address payable beneficiary;
                                    Utils.MegaSwapPath[] path;
                                    address payable partner;
                                    uint256 feePercent;
                                    bytes permit;
                                    uint256 deadline;
                                    bytes16 uuid;
                                }
                                struct SimpleData {
                                    address fromToken;
                                    address toToken;
                                    uint256 fromAmount;
                                    uint256 toAmount;
                                    uint256 expectedAmount;
                                    address[] callees;
                                    bytes exchangeData;
                                    uint256[] startIndexes;
                                    uint256[] values;
                                    address payable beneficiary;
                                    address payable partner;
                                    uint256 feePercent;
                                    bytes permit;
                                    uint256 deadline;
                                    bytes16 uuid;
                                }
                                struct Adapter {
                                    address payable adapter;
                                    uint256 percent;
                                    uint256 networkFee;//NOT USED
                                    Route[] route;
                                }
                                struct Route {
                                    uint256 index;//Adapter at which index needs to be used
                                    address targetExchange;
                                    uint percent;
                                    bytes payload;
                                    uint256 networkFee;//NOT USED - Network fee is associated with 0xv3 trades
                                }
                                struct MegaSwapPath {
                                    uint256 fromAmountPercent;
                                    Path[] path;
                                }
                                struct Path {
                                    address to;
                                    uint256 totalNetworkFee;//NOT USED - Network fee is associated with 0xv3 trades
                                    Adapter[] adapters;
                                }
                                function ethAddress() internal pure returns (address) {return ETH_ADDRESS;}
                                function maxUint() internal pure returns (uint256) {return MAX_UINT;}
                                function approve(
                                    address addressToApprove,
                                    address token,
                                    uint256 amount
                                ) internal {
                                    if (token != ETH_ADDRESS) {
                                        IERC20 _token = IERC20(token);
                                        uint allowance = _token.allowance(address(this), addressToApprove);
                                        if (allowance < amount) {
                                            _token.safeApprove(addressToApprove, 0);
                                            _token.safeIncreaseAllowance(addressToApprove, MAX_UINT);
                                        }
                                    }
                                }
                                function transferTokens(
                                    address token,
                                    address payable destination,
                                    uint256 amount
                                )
                                internal
                                {
                                    if (amount > 0) {
                                        if (token == ETH_ADDRESS) {
                                            (bool result, ) = destination.call{value: amount, gas: 10000}("");
                                            require(result, "Failed to transfer Ether");
                                        }
                                        else {
                                            IERC20(token).safeTransfer(destination, amount);
                                        }
                                    }
                                }
                                function tokenBalance(
                                    address token,
                                    address account
                                )
                                internal
                                view
                                returns (uint256)
                                {
                                    if (token == ETH_ADDRESS) {
                                        return account.balance;
                                    } else {
                                        return IERC20(token).balanceOf(account);
                                    }
                                }
                                function permit(
                                    address token,
                                    bytes memory permit
                                )
                                    internal
                                {
                                    if (permit.length == 32 * 7) {
                                        (bool success,) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit));
                                        require(success, "Permit failed");
                                    }
                                    if (permit.length == 32 * 8) {
                                        (bool success,) = token.call(abi.encodePacked(IERC20PermitLegacy.permit.selector, permit));
                                        require(success, "Permit failed");
                                    }
                                }
                            }
                            // File: original_contracts/routers/IRouter.sol
                            pragma solidity 0.7.5;
                            interface IRouter {
                                /**
                                * @dev Certain routers/exchanges needs to be initialized.
                                * This method will be called from Augustus
                                */
                                function initialize(bytes calldata data) external;
                                /**
                                * @dev Returns unique identifier for the router
                                */
                                function getKey() external pure returns(bytes32);
                                event Swapped2(
                                    bytes16 uuid,
                                    address partner,
                                    uint256 feePercent,
                                    address initiator,
                                    address indexed beneficiary,
                                    address indexed srcToken,
                                    address indexed destToken,
                                    uint256 srcAmount,
                                    uint256 receivedAmount,
                                    uint256 expectedAmount
                                );
                                event Bought2(
                                    bytes16 uuid,
                                    address partner,
                                    uint256 feePercent,
                                    address initiator,
                                    address indexed beneficiary,
                                    address indexed srcToken,
                                    address indexed destToken,
                                    uint256 srcAmount,
                                    uint256 receivedAmount
                                );
                            }
                            // File: original_contracts/lib/weth/IWETH.sol
                            pragma solidity 0.7.5;
                            abstract contract IWETH is IERC20 {
                                function deposit() external virtual payable;
                                function withdraw(uint256 amount) external virtual;
                            }
                            // File: original_contracts/AugustusStorage.sol
                            pragma solidity 0.7.5;
                            contract AugustusStorage {
                                struct FeeStructure {
                                    uint256 partnerShare;
                                    bool noPositiveSlippage;
                                    bool positiveSlippageToUser;
                                    uint16 feePercent;
                                    string partnerId;
                                    bytes data;
                                }
                                ITokenTransferProxy internal tokenTransferProxy;
                                address payable internal feeWallet;
                                
                                mapping(address => FeeStructure) internal registeredPartners;
                                mapping (bytes4 => address) internal selectorVsRouter;
                                mapping (bytes32 => bool) internal adapterInitialized;
                                mapping (bytes32 => bytes) internal adapterVsData;
                                mapping (bytes32 => bytes) internal routerData;
                                mapping (bytes32 => bool) internal routerInitialized;
                                bytes32 public constant WHITELISTED_ROLE = keccak256("WHITELISTED_ROLE");
                                bytes32 public constant ROUTER_ROLE = keccak256("ROUTER_ROLE");
                            }
                            // File: original_contracts/fee/FeeModel.sol
                            pragma solidity 0.7.5;
                            contract FeeModel is AugustusStorage {
                                using SafeMath for uint256;
                                uint256 public immutable partnerSharePercent;
                                uint256 public immutable maxFeePercent;
                                constructor(
                                    uint256 _partnerSharePercent,
                                    uint256 _maxFeePercent
                                )
                                    public
                                {
                                    partnerSharePercent = _partnerSharePercent;
                                    maxFeePercent = _maxFeePercent;
                                }
                                // feePercent is a packed structure.
                                // Bits 255-248 = 8-bit version field
                                //
                                // Version 0
                                // =========
                                // Entire structure is interpreted as the fee percent in basis points.
                                // If set to 0 then partner will not receive any fees.
                                //
                                // Version 1
                                // =========
                                // Bits 13-0 = Fee percent in basis points
                                // Bit 14 = positiveSlippageToUser (positive slippage to partner if not set)
                                function takeFeeAndTransferTokens(
                                    address toToken,
                                    uint256 expectedAmount,
                                    uint256 receivedAmount,
                                    address payable beneficiary,
                                    address payable partner,
                                    uint256 feePercent
                                )
                                    internal
                                {
                                    uint256 fee = 0;
                                    if ( feePercent != 0 && partner != address(0) ) {
                                        uint256 version = feePercent >> 248;
                                        if (version == 0) {
                                            fee = _takeFee(
                                                feePercent > maxFeePercent ? maxFeePercent : feePercent,
                                                toToken,
                                                receivedAmount,
                                                expectedAmount,
                                                partnerSharePercent,
                                                true, //positiveSlippageToUser
                                                partner
                                            );
                                        } else if (version == 1) {
                                            uint256 feeBps = feePercent & 0x3FFF;
                                            fee = _takeFee(
                                                feeBps > maxFeePercent ? maxFeePercent : feeBps,
                                                toToken,
                                                receivedAmount,
                                                expectedAmount,
                                                partnerSharePercent,
                                                (feePercent & (1 << 14)) != 0, //positiveSlippageToUser
                                                partner
                                            );
                                        }
                                    }
                                    uint256 remainingAmount = receivedAmount;
                                    //If there is a positive slippage and no partner fee
                                    //then 50% goes to paraswap and 50% to the user
                                    if (fee == 0) {
                                        if (remainingAmount > expectedAmount) {
                                            uint256 positiveSlippageShare =
                                                remainingAmount.sub(expectedAmount).div(2);
                                            remainingAmount = remainingAmount.sub(positiveSlippageShare);
                                            Utils.transferTokens(toToken, feeWallet, positiveSlippageShare);
                                        }
                                    } else {
                                        remainingAmount = remainingAmount.sub(fee);
                                    }
                                    Utils.transferTokens(toToken, beneficiary, remainingAmount);
                                }
                                function _takeFee(
                                    uint256 feePercent,
                                    address toToken,
                                    uint256 receivedAmount,
                                    uint256 expectedAmount,
                                    uint256 partnerSharePercent,
                                    bool positiveSlippageToUser,
                                    address payable partner
                                )
                                    private
                                    returns(uint256 fee)
                                {
                                    uint256 partnerShare = 0;
                                    uint256 paraswapShare = 0;
                                    bool takeSlippage = feePercent <= 50 && receivedAmount > expectedAmount;
                                    if (feePercent > 0) {
                                        //Calculate total fee to be taken
                                        fee = (takeSlippage ? expectedAmount : receivedAmount)
                                            .mul(feePercent).div(10000);
                                        //Calculate partner's share
                                        partnerShare = fee.mul(partnerSharePercent).div(10000);
                                        //All remaining fee is paraswap's share
                                        paraswapShare = fee.sub(partnerShare);
                                    }
                                    if (takeSlippage) {
                                        uint256 halfPositiveSlippage =
                                            receivedAmount.sub(expectedAmount).div(2);
                                        paraswapShare = paraswapShare.add(halfPositiveSlippage);
                                        fee = fee.add(halfPositiveSlippage);
                                        if (!positiveSlippageToUser) {
                                            partnerShare = partnerShare.add(halfPositiveSlippage);
                                            fee = fee.add(halfPositiveSlippage);
                                        }
                                    }
                                    Utils.transferTokens(toToken, partner, partnerShare);
                                    Utils.transferTokens(toToken, feeWallet, paraswapShare);
                                    return (fee);
                                }
                            }
                            // File: original_contracts/routers/SimpleSwap.sol
                            pragma solidity 0.7.5;
                            contract SimpleSwap is FeeModel, IRouter {
                                using SafeMath for uint256;
                                constructor(
                                    uint256 _partnerSharePercent,
                                    uint256 _maxFeePercent
                                )
                                    FeeModel(
                                        _partnerSharePercent,
                                        _maxFeePercent
                                    )
                                    public
                                {
                                    
                                }
                                function initialize(bytes calldata data) override external {
                                    revert("METHOD NOT IMPLEMENTED");
                                }
                                function getKey() override external pure returns(bytes32) {
                                    return keccak256(abi.encodePacked("SIMPLE_SWAP_ROUTER", "1.0.0"));
                                }
                                function simpleSwap(
                                    Utils.SimpleData memory data
                                )
                                    public
                                    payable
                                    returns (uint256 receivedAmount)
                                {   
                                    require(data.deadline >= block.timestamp, "Deadline breached");
                                    address payable beneficiary = data.beneficiary == address(0) ? msg.sender : data.beneficiary;
                                    receivedAmount = performSimpleSwap(
                                        data.fromToken,
                                        data.toToken,
                                        data.fromAmount,
                                        data.toAmount,
                                        data.expectedAmount,
                                        data.callees,
                                        data.exchangeData,
                                        data.startIndexes,
                                        data.values,
                                        beneficiary,
                                        data.partner,
                                        data.feePercent,
                                        data.permit
                                    );
                                    emit Swapped2(
                                        data.uuid,
                                        data.partner,
                                        data.feePercent,
                                        msg.sender,
                                        beneficiary,
                                        data.fromToken,
                                        data.toToken,
                                        data.fromAmount,
                                        receivedAmount,
                                        data.expectedAmount
                                    );
                                    return receivedAmount;
                                }
                                function simpleBuy(
                                    Utils.SimpleData calldata data
                                )
                                    external
                                    payable
                                {
                                    require(data.deadline >= block.timestamp, "Deadline breached");
                                    address payable beneficiary = data.beneficiary == address(0) ? msg.sender : data.beneficiary;
                                    uint receivedAmount = performSimpleSwap(
                                        data.fromToken,
                                        data.toToken,
                                        data.fromAmount,
                                        data.toAmount,
                                        data.toAmount,//expected amount and to amount are same in case of buy
                                        data.callees,
                                        data.exchangeData,
                                        data.startIndexes,
                                        data.values,
                                        beneficiary,
                                        data.partner,
                                        data.feePercent,
                                        data.permit
                                    );
                                    uint256 remainingAmount = Utils.tokenBalance(
                                        data.fromToken,
                                        address(this)
                                    );
                                    if (remainingAmount > 0) {
                                        Utils.transferTokens(address(data.fromToken), msg.sender, remainingAmount);
                                    }
                                    emit Bought2(
                                        data.uuid,
                                        data.partner,
                                        data.feePercent,
                                        msg.sender,
                                        beneficiary,
                                        data.fromToken,
                                        data.toToken,
                                        data.fromAmount,
                                        receivedAmount
                                    );
                                }
                                function performSimpleSwap(
                                    address fromToken,
                                    address toToken,
                                    uint256 fromAmount,
                                    uint256 toAmount,
                                    uint256 expectedAmount,
                                    address[] memory callees,
                                    bytes memory exchangeData,
                                    uint256[] memory startIndexes,
                                    uint256[] memory values,
                                    address payable beneficiary,
                                    address payable partner,
                                    uint256 feePercent,
                                    bytes memory permit
                                )
                                    private
                                    returns (uint256 receivedAmount)
                                {
                                    require(msg.value == (fromToken == Utils.ethAddress() ? fromAmount : 0),
                                        "Incorrect msg.value");
                                    require(toAmount > 0, "toAmount is too low");
                                    require(
                                        callees.length + 1 == startIndexes.length,
                                        "Start indexes must be 1 greater then number of callees"
                                    );
                                    //If source token is not ETH than transfer required amount of tokens
                                    //from sender to this contract
                                    transferTokensFromProxy(fromToken, fromAmount, permit);
                                    for (uint256 i = 0; i < callees.length; i++) {
                                        require(
                                            callees[i] != address(tokenTransferProxy),
                                            "Can not call TokenTransferProxy Contract"
                                        );
                                        {
                                            uint256 dataOffset = startIndexes[i];
                                            bytes32 selector;
                                            assembly {
                                                selector := mload(add(exchangeData, add(dataOffset, 32)))
                                            }
                                            require(
                                                bytes4(selector) != IERC20.transferFrom.selector,
                                                "transferFrom not allowed for externalCall"
                                            );
                                        }
                                        bool result = externalCall(
                                            callees[i], //destination
                                            values[i], //value to send
                                            startIndexes[i], // start index of call data
                                            startIndexes[i + 1].sub(startIndexes[i]), // length of calldata
                                            exchangeData// total calldata
                                        );
                                        require(result, "External call failed");
                                    }
                                    receivedAmount = Utils.tokenBalance(
                                        toToken,
                                        address(this)
                                    );
                                    require(
                                        receivedAmount >= toAmount,
                                        "Received amount of tokens are less then expected"
                                    );
                                    takeFeeAndTransferTokens(
                                        toToken,
                                        expectedAmount,
                                        receivedAmount,
                                        beneficiary,
                                        partner,
                                        feePercent
                                    );
                                    return receivedAmount;
                                }
                                function transferTokensFromProxy(
                                    address token,
                                    uint256 amount,
                                    bytes memory permit
                                )
                                  private
                                {
                                    if (token != Utils.ethAddress()) {
                                        Utils.permit(token, permit);
                                        tokenTransferProxy.transferFrom(
                                            token,
                                            msg.sender,
                                            address(this),
                                            amount
                                        );
                                    }
                                }
                                /**
                                * @dev Source take from GNOSIS MultiSigWallet
                                * @dev https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol
                                */
                                function externalCall(
                                    address destination,
                                    uint256 value,
                                    uint256 dataOffset,
                                    uint dataLength,
                                    bytes memory data
                                )
                                private
                                returns (bool)
                                {
                                    bool result = false;
                                    assembly {
                                        let x := mload(0x40)   // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
                                        let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
                                        result := call(
                                            gas(),
                                            destination,
                                            value,
                                            add(d, dataOffset),
                                            dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
                                            x,
                                            0                  // Output is ignored, therefore the output size is zero
                                        )
                                    }
                                    return result;
                                }
                            }
                            

                            File 8 of 12: TokenTransferProxy
                            // File: openzeppelin-solidity/contracts/utils/EnumerableSet.sol
                            
                            
                            
                            pragma solidity >=0.6.0 <0.8.0;
                            
                            /**
                             * @dev Library for managing
                             * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
                             * types.
                             *
                             * Sets have the following properties:
                             *
                             * - Elements are added, removed, and checked for existence in constant time
                             * (O(1)).
                             * - Elements are enumerated in O(n). No guarantees are made on the ordering.
                             *
                             * ```
                             * contract Example {
                             *     // Add the library methods
                             *     using EnumerableSet for EnumerableSet.AddressSet;
                             *
                             *     // Declare a set state variable
                             *     EnumerableSet.AddressSet private mySet;
                             * }
                             * ```
                             *
                             * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
                             * and `uint256` (`UintSet`) are supported.
                             */
                            library EnumerableSet {
                                // To implement this library for multiple types with as little code
                                // repetition as possible, we write it in terms of a generic Set type with
                                // bytes32 values.
                                // The Set implementation uses private functions, and user-facing
                                // implementations (such as AddressSet) are just wrappers around the
                                // underlying Set.
                                // This means that we can only create new EnumerableSets for types that fit
                                // in bytes32.
                            
                                struct Set {
                                    // Storage of set values
                                    bytes32[] _values;
                            
                                    // Position of the value in the `values` array, plus 1 because index 0
                                    // means a value is not in the set.
                                    mapping (bytes32 => uint256) _indexes;
                                }
                            
                                /**
                                 * @dev Add a value to a set. O(1).
                                 *
                                 * Returns true if the value was added to the set, that is if it was not
                                 * already present.
                                 */
                                function _add(Set storage set, bytes32 value) private returns (bool) {
                                    if (!_contains(set, value)) {
                                        set._values.push(value);
                                        // The value is stored at length-1, but we add 1 to all indexes
                                        // and use 0 as a sentinel value
                                        set._indexes[value] = set._values.length;
                                        return true;
                                    } else {
                                        return false;
                                    }
                                }
                            
                                /**
                                 * @dev Removes a value from a set. O(1).
                                 *
                                 * Returns true if the value was removed from the set, that is if it was
                                 * present.
                                 */
                                function _remove(Set storage set, bytes32 value) private returns (bool) {
                                    // We read and store the value's index to prevent multiple reads from the same storage slot
                                    uint256 valueIndex = set._indexes[value];
                            
                                    if (valueIndex != 0) { // Equivalent to contains(set, value)
                                        // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                                        // the array, and then remove the last element (sometimes called as 'swap and pop').
                                        // This modifies the order of the array, as noted in {at}.
                            
                                        uint256 toDeleteIndex = valueIndex - 1;
                                        uint256 lastIndex = set._values.length - 1;
                            
                                        // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
                                        // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
                            
                                        bytes32 lastvalue = set._values[lastIndex];
                            
                                        // Move the last value to the index where the value to delete is
                                        set._values[toDeleteIndex] = lastvalue;
                                        // Update the index for the moved value
                                        set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
                            
                                        // Delete the slot where the moved value was stored
                                        set._values.pop();
                            
                                        // Delete the index for the deleted slot
                                        delete set._indexes[value];
                            
                                        return true;
                                    } else {
                                        return false;
                                    }
                                }
                            
                                /**
                                 * @dev Returns true if the value is in the set. O(1).
                                 */
                                function _contains(Set storage set, bytes32 value) private view returns (bool) {
                                    return set._indexes[value] != 0;
                                }
                            
                                /**
                                 * @dev Returns the number of values on the set. O(1).
                                 */
                                function _length(Set storage set) private view returns (uint256) {
                                    return set._values.length;
                                }
                            
                               /**
                                * @dev Returns the value stored at position `index` in the set. O(1).
                                *
                                * Note that there are no guarantees on the ordering of values inside the
                                * array, and it may change when more values are added or removed.
                                *
                                * Requirements:
                                *
                                * - `index` must be strictly less than {length}.
                                */
                                function _at(Set storage set, uint256 index) private view returns (bytes32) {
                                    require(set._values.length > index, "EnumerableSet: index out of bounds");
                                    return set._values[index];
                                }
                            
                                // Bytes32Set
                            
                                struct Bytes32Set {
                                    Set _inner;
                                }
                            
                                /**
                                 * @dev Add a value to a set. O(1).
                                 *
                                 * Returns true if the value was added to the set, that is if it was not
                                 * already present.
                                 */
                                function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                                    return _add(set._inner, value);
                                }
                            
                                /**
                                 * @dev Removes a value from a set. O(1).
                                 *
                                 * Returns true if the value was removed from the set, that is if it was
                                 * present.
                                 */
                                function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                                    return _remove(set._inner, value);
                                }
                            
                                /**
                                 * @dev Returns true if the value is in the set. O(1).
                                 */
                                function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                                    return _contains(set._inner, value);
                                }
                            
                                /**
                                 * @dev Returns the number of values in the set. O(1).
                                 */
                                function length(Bytes32Set storage set) internal view returns (uint256) {
                                    return _length(set._inner);
                                }
                            
                               /**
                                * @dev Returns the value stored at position `index` in the set. O(1).
                                *
                                * Note that there are no guarantees on the ordering of values inside the
                                * array, and it may change when more values are added or removed.
                                *
                                * Requirements:
                                *
                                * - `index` must be strictly less than {length}.
                                */
                                function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                                    return _at(set._inner, index);
                                }
                            
                                // AddressSet
                            
                                struct AddressSet {
                                    Set _inner;
                                }
                            
                                /**
                                 * @dev Add a value to a set. O(1).
                                 *
                                 * Returns true if the value was added to the set, that is if it was not
                                 * already present.
                                 */
                                function add(AddressSet storage set, address value) internal returns (bool) {
                                    return _add(set._inner, bytes32(uint256(value)));
                                }
                            
                                /**
                                 * @dev Removes a value from a set. O(1).
                                 *
                                 * Returns true if the value was removed from the set, that is if it was
                                 * present.
                                 */
                                function remove(AddressSet storage set, address value) internal returns (bool) {
                                    return _remove(set._inner, bytes32(uint256(value)));
                                }
                            
                                /**
                                 * @dev Returns true if the value is in the set. O(1).
                                 */
                                function contains(AddressSet storage set, address value) internal view returns (bool) {
                                    return _contains(set._inner, bytes32(uint256(value)));
                                }
                            
                                /**
                                 * @dev Returns the number of values in the set. O(1).
                                 */
                                function length(AddressSet storage set) internal view returns (uint256) {
                                    return _length(set._inner);
                                }
                            
                               /**
                                * @dev Returns the value stored at position `index` in the set. O(1).
                                *
                                * Note that there are no guarantees on the ordering of values inside the
                                * array, and it may change when more values are added or removed.
                                *
                                * Requirements:
                                *
                                * - `index` must be strictly less than {length}.
                                */
                                function at(AddressSet storage set, uint256 index) internal view returns (address) {
                                    return address(uint256(_at(set._inner, index)));
                                }
                            
                            
                                // UintSet
                            
                                struct UintSet {
                                    Set _inner;
                                }
                            
                                /**
                                 * @dev Add a value to a set. O(1).
                                 *
                                 * Returns true if the value was added to the set, that is if it was not
                                 * already present.
                                 */
                                function add(UintSet storage set, uint256 value) internal returns (bool) {
                                    return _add(set._inner, bytes32(value));
                                }
                            
                                /**
                                 * @dev Removes a value from a set. O(1).
                                 *
                                 * Returns true if the value was removed from the set, that is if it was
                                 * present.
                                 */
                                function remove(UintSet storage set, uint256 value) internal returns (bool) {
                                    return _remove(set._inner, bytes32(value));
                                }
                            
                                /**
                                 * @dev Returns true if the value is in the set. O(1).
                                 */
                                function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                                    return _contains(set._inner, bytes32(value));
                                }
                            
                                /**
                                 * @dev Returns the number of values on the set. O(1).
                                 */
                                function length(UintSet storage set) internal view returns (uint256) {
                                    return _length(set._inner);
                                }
                            
                               /**
                                * @dev Returns the value stored at position `index` in the set. O(1).
                                *
                                * Note that there are no guarantees on the ordering of values inside the
                                * array, and it may change when more values are added or removed.
                                *
                                * Requirements:
                                *
                                * - `index` must be strictly less than {length}.
                                */
                                function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                                    return uint256(_at(set._inner, index));
                                }
                            }
                            
                            // File: openzeppelin-solidity/contracts/utils/Address.sol
                            
                            
                            
                            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: openzeppelin-solidity/contracts/GSN/Context.sol
                            
                            
                            
                            pragma solidity >=0.6.0 <0.8.0;
                            
                            /*
                             * @dev Provides information about the current execution context, including the
                             * sender of the transaction and its data. While these are generally available
                             * via msg.sender and msg.data, they should not be accessed in such a direct
                             * manner, since when dealing with GSN meta-transactions the account sending and
                             * paying for execution may not be the actual sender (as far as an application
                             * is concerned).
                             *
                             * This contract is only required for intermediate, library-like contracts.
                             */
                            abstract contract Context {
                                function _msgSender() internal view virtual returns (address payable) {
                                    return msg.sender;
                                }
                            
                                function _msgData() internal view virtual returns (bytes memory) {
                                    this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                                    return msg.data;
                                }
                            }
                            
                            // File: openzeppelin-solidity/contracts/access/AccessControl.sol
                            
                            
                            
                            pragma solidity >=0.6.0 <0.8.0;
                            
                            
                            
                            
                            /**
                             * @dev Contract module that allows children to implement role-based access
                             * control mechanisms.
                             *
                             * Roles are referred to by their `bytes32` identifier. These should be exposed
                             * in the external API and be unique. The best way to achieve this is by
                             * using `public constant` hash digests:
                             *
                             * ```
                             * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
                             * ```
                             *
                             * Roles can be used to represent a set of permissions. To restrict access to a
                             * function call, use {hasRole}:
                             *
                             * ```
                             * function foo() public {
                             *     require(hasRole(MY_ROLE, msg.sender));
                             *     ...
                             * }
                             * ```
                             *
                             * Roles can be granted and revoked dynamically via the {grantRole} and
                             * {revokeRole} functions. Each role has an associated admin role, and only
                             * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
                             *
                             * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
                             * that only accounts with this role will be able to grant or revoke other
                             * roles. More complex role relationships can be created by using
                             * {_setRoleAdmin}.
                             *
                             * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
                             * grant and revoke this role. Extra precautions should be taken to secure
                             * accounts that have been granted it.
                             */
                            abstract contract AccessControl is Context {
                                using EnumerableSet for EnumerableSet.AddressSet;
                                using Address for address;
                            
                                struct RoleData {
                                    EnumerableSet.AddressSet members;
                                    bytes32 adminRole;
                                }
                            
                                mapping (bytes32 => RoleData) private _roles;
                            
                                bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
                            
                                /**
                                 * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
                                 *
                                 * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
                                 * {RoleAdminChanged} not being emitted signaling this.
                                 *
                                 * _Available since v3.1._
                                 */
                                event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
                            
                                /**
                                 * @dev Emitted when `account` is granted `role`.
                                 *
                                 * `sender` is the account that originated the contract call, an admin role
                                 * bearer except when using {_setupRole}.
                                 */
                                event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
                            
                                /**
                                 * @dev Emitted when `account` is revoked `role`.
                                 *
                                 * `sender` is the account that originated the contract call:
                                 *   - if using `revokeRole`, it is the admin role bearer
                                 *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
                                 */
                                event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
                            
                                /**
                                 * @dev Returns `true` if `account` has been granted `role`.
                                 */
                                function hasRole(bytes32 role, address account) public view returns (bool) {
                                    return _roles[role].members.contains(account);
                                }
                            
                                /**
                                 * @dev Returns the number of accounts that have `role`. Can be used
                                 * together with {getRoleMember} to enumerate all bearers of a role.
                                 */
                                function getRoleMemberCount(bytes32 role) public view returns (uint256) {
                                    return _roles[role].members.length();
                                }
                            
                                /**
                                 * @dev Returns one of the accounts that have `role`. `index` must be a
                                 * value between 0 and {getRoleMemberCount}, non-inclusive.
                                 *
                                 * Role bearers are not sorted in any particular way, and their ordering may
                                 * change at any point.
                                 *
                                 * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
                                 * you perform all queries on the same block. See the following
                                 * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
                                 * for more information.
                                 */
                                function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
                                    return _roles[role].members.at(index);
                                }
                            
                                /**
                                 * @dev Returns the admin role that controls `role`. See {grantRole} and
                                 * {revokeRole}.
                                 *
                                 * To change a role's admin, use {_setRoleAdmin}.
                                 */
                                function getRoleAdmin(bytes32 role) public view returns (bytes32) {
                                    return _roles[role].adminRole;
                                }
                            
                                /**
                                 * @dev Grants `role` to `account`.
                                 *
                                 * If `account` had not been already granted `role`, emits a {RoleGranted}
                                 * event.
                                 *
                                 * Requirements:
                                 *
                                 * - the caller must have ``role``'s admin role.
                                 */
                                function grantRole(bytes32 role, address account) public virtual {
                                    require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
                            
                                    _grantRole(role, account);
                                }
                            
                                /**
                                 * @dev Revokes `role` from `account`.
                                 *
                                 * If `account` had been granted `role`, emits a {RoleRevoked} event.
                                 *
                                 * Requirements:
                                 *
                                 * - the caller must have ``role``'s admin role.
                                 */
                                function revokeRole(bytes32 role, address account) public virtual {
                                    require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
                            
                                    _revokeRole(role, account);
                                }
                            
                                /**
                                 * @dev Revokes `role` from the calling account.
                                 *
                                 * Roles are often managed via {grantRole} and {revokeRole}: this function's
                                 * purpose is to provide a mechanism for accounts to lose their privileges
                                 * if they are compromised (such as when a trusted device is misplaced).
                                 *
                                 * If the calling account had been granted `role`, emits a {RoleRevoked}
                                 * event.
                                 *
                                 * Requirements:
                                 *
                                 * - the caller must be `account`.
                                 */
                                function renounceRole(bytes32 role, address account) public virtual {
                                    require(account == _msgSender(), "AccessControl: can only renounce roles for self");
                            
                                    _revokeRole(role, account);
                                }
                            
                                /**
                                 * @dev Grants `role` to `account`.
                                 *
                                 * If `account` had not been already granted `role`, emits a {RoleGranted}
                                 * event. Note that unlike {grantRole}, this function doesn't perform any
                                 * checks on the calling account.
                                 *
                                 * [WARNING]
                                 * ====
                                 * This function should only be called from the constructor when setting
                                 * up the initial roles for the system.
                                 *
                                 * Using this function in any other way is effectively circumventing the admin
                                 * system imposed by {AccessControl}.
                                 * ====
                                 */
                                function _setupRole(bytes32 role, address account) internal virtual {
                                    _grantRole(role, account);
                                }
                            
                                /**
                                 * @dev Sets `adminRole` as ``role``'s admin role.
                                 *
                                 * Emits a {RoleAdminChanged} event.
                                 */
                                function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
                                    emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
                                    _roles[role].adminRole = adminRole;
                                }
                            
                                function _grantRole(bytes32 role, address account) private {
                                    if (_roles[role].members.add(account)) {
                                        emit RoleGranted(role, account, _msgSender());
                                    }
                                }
                            
                                function _revokeRole(bytes32 role, address account) private {
                                    if (_roles[role].members.remove(account)) {
                                        emit RoleRevoked(role, account, _msgSender());
                                    }
                                }
                            }
                            
                            // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
                            
                            
                            
                            pragma solidity >=0.6.0 <0.8.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: openzeppelin-solidity/contracts/math/SafeMath.sol
                            
                            
                            
                            pragma solidity >=0.6.0 <0.8.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-solidity/contracts/token/ERC20/SafeERC20.sol
                            
                            
                            
                            pragma solidity >=0.6.0 <0.8.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: original_contracts/routers/IRouter.sol
                            
                            pragma solidity 0.7.5;
                            
                            interface IRouter {
                            
                                /**
                                * @dev Certain routers/exchanges needs to be initialized.
                                * This method will be called from Augustus
                                */
                                function initialize(bytes calldata data) external;
                            
                                /**
                                * @dev Returns unique identifier for the router
                                */
                                function getKey() external pure returns(bytes32);
                            
                                event Swapped(
                                    bytes16 uuid,
                                    address initiator,
                                    address indexed beneficiary,
                                    address indexed srcToken,
                                    address indexed destToken,
                                    uint256 srcAmount,
                                    uint256 receivedAmount,
                                    uint256 expectedAmount
                                );
                            
                                event Bought(
                                    bytes16 uuid,
                                    address initiator,
                                    address indexed beneficiary,
                                    address indexed srcToken,
                                    address indexed destToken,
                                    uint256 srcAmount,
                                    uint256 receivedAmount
                                );
                            
                                event FeeTaken(
                                    uint256 fee,
                                    uint256 partnerShare,
                                    uint256 paraswapShare
                                );
                            }
                            
                            // File: original_contracts/ITokenTransferProxy.sol
                            
                            pragma solidity 0.7.5;
                            
                            
                            interface ITokenTransferProxy {
                            
                                function transferFrom(
                                    address token,
                                    address from,
                                    address to,
                                    uint256 amount
                                )
                                    external;
                            }
                            
                            // File: original_contracts/lib/Utils.sol
                            
                            pragma solidity 0.7.5;
                            pragma experimental ABIEncoderV2;
                            
                            
                            
                            
                            
                            interface IERC20Permit {
                                function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
                            }
                            
                            library Utils {
                                using SafeMath for uint256;
                                using SafeERC20 for IERC20;
                            
                                address constant ETH_ADDRESS = address(
                                    0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
                                );
                                
                                uint256 constant MAX_UINT = type(uint256).max;
                            
                                /**
                               * @param fromToken Address of the source token
                               * @param fromAmount Amount of source tokens to be swapped
                               * @param toAmount Minimum destination token amount expected out of this swap
                               * @param expectedAmount Expected amount of destination tokens without slippage
                               * @param beneficiary Beneficiary address
                               * 0 then 100% will be transferred to beneficiary. Pass 10000 for 100%
                               * @param path Route to be taken for this swap to take place
                            
                               */
                                struct SellData {
                                    address fromToken;
                                    uint256 fromAmount;
                                    uint256 toAmount;
                                    uint256 expectedAmount;
                                    address payable beneficiary;
                                    Utils.Path[] path;
                                    address payable partner;
                                    uint256 feePercent;
                                    bytes permit;
                                    uint256 deadline;
                                    bytes16 uuid;
                                }
                            
                                struct MegaSwapSellData {
                                    address fromToken;
                                    uint256 fromAmount;
                                    uint256 toAmount;
                                    uint256 expectedAmount;
                                    address payable beneficiary;
                                    Utils.MegaSwapPath[] path;
                                    address payable partner;
                                    uint256 feePercent;
                                    bytes permit;
                                    uint256 deadline;
                                    bytes16 uuid;
                                }
                            
                                struct SimpleData {
                                    address fromToken;
                                    address toToken;
                                    uint256 fromAmount;
                                    uint256 toAmount;
                                    uint256 expectedAmount;
                                    address[] callees;
                                    bytes exchangeData;
                                    uint256[] startIndexes;
                                    uint256[] values;
                                    address payable beneficiary;
                                    address payable partner;
                                    uint256 feePercent;
                                    bytes permit;
                                    uint256 deadline;
                                    bytes16 uuid;
                                }
                            
                                struct Adapter {
                                    address payable adapter;
                                    uint256 percent;
                                    uint256 networkFee;
                                    Route[] route;
                                }
                            
                                struct Route {
                                    uint256 index;//Adapter at which index needs to be used
                                    address targetExchange;
                                    uint percent;
                                    bytes payload;
                                    uint256 networkFee;//Network fee is associated with 0xv3 trades
                                }
                            
                                struct MegaSwapPath {
                                    uint256 fromAmountPercent;
                                    Path[] path;
                                }
                            
                                struct Path {
                                    address to;
                                    uint256 totalNetworkFee;//Network fee is associated with 0xv3 trades
                                    Adapter[] adapters;
                                }
                            
                                function ethAddress() internal pure returns (address) {return ETH_ADDRESS;}
                            
                                function maxUint() internal pure returns (uint256) {return MAX_UINT;}
                            
                                function approve(
                                    address addressToApprove,
                                    address token,
                                    uint256 amount
                                ) internal {
                                    if (token != ETH_ADDRESS) {
                                        IERC20 _token = IERC20(token);
                            
                                        uint allowance = _token.allowance(address(this), addressToApprove);
                            
                                        if (allowance < amount) {
                                            _token.safeApprove(addressToApprove, 0);
                                            _token.safeIncreaseAllowance(addressToApprove, MAX_UINT);
                                        }
                                    }
                                }
                            
                                function transferTokens(
                                    address token,
                                    address payable destination,
                                    uint256 amount
                                )
                                internal
                                {
                                    if (amount > 0) {
                                        if (token == ETH_ADDRESS) {
                                            (bool result, ) = destination.call{value: amount, gas: 10000}("");
                                            require(result, "Failed to transfer Ether");
                                        }
                                        else {
                                            IERC20(token).safeTransfer(destination, amount);
                                        }
                                    }
                            
                                }
                            
                                function tokenBalance(
                                    address token,
                                    address account
                                )
                                internal
                                view
                                returns (uint256)
                                {
                                    if (token == ETH_ADDRESS) {
                                        return account.balance;
                                    } else {
                                        return IERC20(token).balanceOf(account);
                                    }
                                }
                            
                                function permit(
                                    address token,
                                    bytes memory permit
                                )
                                    internal
                                {
                                    if (permit.length == 32 * 7) {
                                        (bool success,) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit));
                                        require(success, "Permit failed");
                                    }
                                }
                            
                            }
                            
                            // File: original_contracts/adapters/IAdapter.sol
                            
                            pragma solidity 0.7.5;
                            
                            
                            
                            interface IAdapter {
                            
                                /**
                                * @dev Certain adapters needs to be initialized.
                                * This method will be called from Augustus
                                */
                                function initialize(bytes calldata data) external;
                            
                                /**
                               * @dev The function which performs the swap on an exchange.
                               * @param fromToken Address of the source token
                               * @param toToken Address of the destination token
                               * @param fromAmount Amount of source tokens to be swapped
                               * @param networkFee Network fee to be used in this router
                               * @param route Route to be followed
                               */
                                function swap(
                                    IERC20 fromToken,
                                    IERC20 toToken,
                                    uint256 fromAmount,
                                    uint256 networkFee,
                                    Utils.Route[] calldata route
                                )
                                    external
                                    payable;
                            }
                            
                            // File: openzeppelin-solidity/contracts/access/Ownable.sol
                            
                            
                            
                            pragma solidity >=0.6.0 <0.8.0;
                            
                            /**
                             * @dev Contract module which provides a basic access control mechanism, where
                             * there is an account (an owner) that can be granted exclusive access to
                             * specific functions.
                             *
                             * By default, the owner account will be the one that deploys the contract. This
                             * can later be changed with {transferOwnership}.
                             *
                             * This module is used through inheritance. It will make available the modifier
                             * `onlyOwner`, which can be applied to your functions to restrict their use to
                             * the owner.
                             */
                            abstract contract Ownable is Context {
                                address private _owner;
                            
                                event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                            
                                /**
                                 * @dev Initializes the contract setting the deployer as the initial owner.
                                 */
                                constructor () internal {
                                    address msgSender = _msgSender();
                                    _owner = msgSender;
                                    emit OwnershipTransferred(address(0), msgSender);
                                }
                            
                                /**
                                 * @dev Returns the address of the current owner.
                                 */
                                function owner() public view returns (address) {
                                    return _owner;
                                }
                            
                                /**
                                 * @dev Throws if called by any account other than the owner.
                                 */
                                modifier onlyOwner() {
                                    require(_owner == _msgSender(), "Ownable: caller is not the owner");
                                    _;
                                }
                            
                                /**
                                 * @dev Leaves the contract without owner. It will not be possible to call
                                 * `onlyOwner` functions anymore. Can only be called by the current owner.
                                 *
                                 * NOTE: Renouncing ownership will leave the contract without an owner,
                                 * thereby removing any functionality that is only available to the owner.
                                 */
                                function renounceOwnership() public virtual onlyOwner {
                                    emit OwnershipTransferred(_owner, address(0));
                                    _owner = address(0);
                                }
                            
                                /**
                                 * @dev Transfers ownership of the contract to a new account (`newOwner`).
                                 * Can only be called by the current owner.
                                 */
                                function transferOwnership(address newOwner) public virtual onlyOwner {
                                    require(newOwner != address(0), "Ownable: new owner is the zero address");
                                    emit OwnershipTransferred(_owner, newOwner);
                                    _owner = newOwner;
                                }
                            }
                            
                            // File: original_contracts/TokenTransferProxy.sol
                            
                            pragma solidity 0.7.5;
                            
                            
                            
                            
                            
                            
                            
                            /**
                            * @dev Allows owner of the contract to transfer tokens on behalf of user.
                            * User will need to approve this contract to spend tokens on his/her behalf
                            * on Paraswap platform
                            */
                            contract TokenTransferProxy is Ownable, ITokenTransferProxy {
                                using SafeERC20 for IERC20;
                                using Address for address;
                            
                                /**
                                * @dev Allows owner of the contract to transfer tokens on user's behalf
                                * @dev Swapper contract will be the owner of this contract
                                * @param token Address of the token
                                * @param from Address from which tokens will be transferred
                                * @param to Receipent address of the tokens
                                * @param amount Amount of tokens to transfer
                                */
                                function transferFrom(
                                    address token,
                                    address from,
                                    address to,
                                    uint256 amount
                                )
                                    external
                                    override
                                    onlyOwner
                                {   
                                    require(
                                        from == tx.origin ||
                                        from.isContract(),
                                        "Invalid from address"
                                    );
                                    
                                    IERC20(token).safeTransferFrom(from, to, amount);
                                }
                            }
                            
                            // File: original_contracts/AugustusStorage.sol
                            
                            pragma solidity 0.7.5;
                            
                            
                            contract AugustusStorage {
                            
                                struct FeeStructure {
                                    uint256 partnerShare;
                                    bool noPositiveSlippage;
                                    bool positiveSlippageToUser;
                                    uint16 feePercent;
                                    string partnerId;
                                    bytes data;
                                }
                            
                                ITokenTransferProxy internal tokenTransferProxy;
                                address payable internal feeWallet;
                                
                                mapping(address => FeeStructure) internal registeredPartners;
                            
                                mapping (bytes4 => address) internal selectorVsRouter;
                                mapping (bytes32 => bool) internal adapterInitialized;
                                mapping (bytes32 => bytes) internal adapterVsData;
                            
                                mapping (bytes32 => bytes) internal routerData;
                                mapping (bytes32 => bool) internal routerInitialized;
                            
                            
                                bytes32 public constant WHITELISTED_ROLE = keccak256("WHITELISTED_ROLE");
                            
                                bytes32 public constant ROUTER_ROLE = keccak256("ROUTER_ROLE");
                            
                            }
                            
                            // File: original_contracts/AugustusSwapper.sol
                            
                            pragma solidity 0.7.5;
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            contract AugustusSwapper is AugustusStorage, AccessControl {
                                using SafeMath for uint256;
                                using SafeERC20 for IERC20;
                            
                                event AdapterInitialized(address indexed adapter);
                            
                                event RouterInitialized(address indexed router);
                            
                                /**
                                 * @dev Throws if called by any account other than the admin.
                                 */
                                modifier onlyAdmin() {
                                    require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "caller is not the admin");
                                    _;
                                }
                            
                                constructor(address payable _feeWallet) public {
                                    TokenTransferProxy lTokenTransferProxy = new TokenTransferProxy();
                                    tokenTransferProxy = ITokenTransferProxy(lTokenTransferProxy);
                                    feeWallet = _feeWallet;
                                    _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
                                }
                                
                                receive () payable external {
                            
                                }
                            
                                fallback() external payable {
                                    bytes4 selector = msg.sig;
                                    //Figure out the router contract for the given function
                                    address implementation = getImplementation(selector);
                                    if (implementation == address(0)) {
                                        _revertWithData(
                                            abi.encodeWithSelector(
                                                bytes4(keccak256("NotImplementedError(bytes4)")),
                                                selector
                                            )
                                        );
                                    }
                            
                                    //Delegate call to the router
                                    (bool success, bytes memory resultData) = implementation.delegatecall(msg.data);
                                    if (!success) {
                                        _revertWithData(resultData);
                                    }
                            
                                    _returnWithData(resultData);
                                }
                            
                                function initializeAdapter(address adapter, bytes calldata data) external onlyAdmin {
                            
                                    require(
                                        hasRole(WHITELISTED_ROLE, adapter),
                                        "Exchange not whitelisted"
                                    );
                                    (bool success,) = adapter.delegatecall(abi.encodeWithSelector(IAdapter.initialize.selector, data));
                                    require(success, "Failed to initialize adapter");
                                    emit AdapterInitialized(adapter);
                                }
                            
                                function initializeRouter(address router, bytes calldata data) external onlyAdmin {
                            
                                    require(
                                        hasRole(ROUTER_ROLE, router),
                                        "Router not whitelisted"
                                    );
                                    (bool success,) = router.delegatecall(abi.encodeWithSelector(IRouter.initialize.selector, data));
                                    require(success, "Failed to initialize router");
                                    emit RouterInitialized(router);
                                } 
                            
                                
                                function getImplementation(bytes4 selector) public view returns(address) {
                                    return selectorVsRouter[selector];
                                }
                            
                                function getVersion() external pure returns(string memory) {
                                    return "5.0.0";
                                }
                            
                                function getPartnerFeeStructure(address partner) public view returns (FeeStructure memory) {
                                    return registeredPartners[partner];
                                }
                            
                                function getFeeWallet() external view returns(address) {
                                    return feeWallet;
                                }
                            
                                function setFeeWallet(address payable _feeWallet) external onlyAdmin {
                                    require(_feeWallet != address(0), "Invalid address");
                                    feeWallet = _feeWallet;
                                }
                            
                                function registerPartner(
                                    address partner,
                                    uint256 _partnerShare,
                                    bool _noPositiveSlippage,
                                    bool _positiveSlippageToUser,
                                    uint16 _feePercent,
                                    string calldata partnerId,
                                    bytes calldata _data
                                )
                                    external
                                    onlyAdmin
                                {   
                                    require(partner != address(0), "Invalid partner");
                                    FeeStructure storage feeStructure = registeredPartners[partner];
                                    require(feeStructure.partnerShare == 0, "Already registered");
                                    require(_partnerShare > 0 && _partnerShare < 10000, "Invalid values");
                                    require(_feePercent <= 10000, "Invalid values");
                            
                                    feeStructure.partnerShare = _partnerShare;
                                    feeStructure.noPositiveSlippage = _noPositiveSlippage;
                                    feeStructure.positiveSlippageToUser = _positiveSlippageToUser;
                                    feeStructure.partnerId = partnerId;
                                    feeStructure.feePercent = _feePercent;
                                    feeStructure.data = _data;
                                }
                            
                                function setImplementation(bytes4 selector, address implementation) external onlyAdmin {
                                    require(
                                        hasRole(ROUTER_ROLE, implementation),
                                        "Router is not whitelisted"
                                    );
                                    selectorVsRouter[selector] = implementation;
                                }
                            
                                /**
                                * @dev Allows admin of the contract to transfer any tokens which are assigned to the contract
                                * This method is for safety if by any chance tokens or ETHs are assigned to the contract by mistake
                                * @dev token Address of the token to be transferred
                                * @dev destination Recepient of the token
                                * @dev amount Amount of tokens to be transferred
                                */
                                function transferTokens(
                                    address token,
                                    address payable destination,
                                    uint256 amount
                                )
                                    external
                                    onlyAdmin
                                {
                                    if (amount > 0) {
                                        if (token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) {
                                            (bool result, ) = destination.call{value: amount, gas: 10000}("");
                                            require(result, "Failed to transfer Ether");
                                        }
                                        else {
                                            IERC20(token).safeTransfer(destination, amount);
                                        }
                                    }
                                }
                            
                                  function isAdapterInitialized(bytes32 key) public view returns(bool) {
                                    return adapterInitialized[key];
                                }
                            
                                function getAdapterData(bytes32 key) public view returns(bytes memory) {
                                    return adapterVsData[key];
                                }
                            
                                function isRouterInitialized(bytes32 key) public view returns (bool) {
                                    return routerInitialized[key];
                                }
                            
                                function getRouterData(bytes32 key) public view returns (bytes memory) {
                                    return routerData[key];
                                }
                            
                                function getTokenTransferProxy() public view returns (address) {
                                    return address(tokenTransferProxy);
                                }
                            
                                function _revertWithData(bytes memory data) private pure {
                                    assembly { revert(add(data, 32), mload(data)) }
                                }
                            
                                function _returnWithData(bytes memory data) private pure {
                                    assembly { return(add(data, 32), mload(data)) }
                                }
                            
                            }

                            File 9 of 12: KernelProxy
                            /**
                             *Submitted for verification at Etherscan.io on 2020-02-06
                            */
                            
                            // File: contracts/acl/IACL.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            interface IACL {
                                function initialize(address permissionsCreator) external;
                            
                                // TODO: this should be external
                                // See https://github.com/ethereum/solidity/issues/4832
                                function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                            }
                            
                            // File: contracts/common/IVaultRecoverable.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            interface IVaultRecoverable {
                                event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
                            
                                function transferToVault(address token) external;
                            
                                function allowRecoverability(address token) external view returns (bool);
                                function getRecoveryVault() external view returns (address);
                            }
                            
                            // File: contracts/kernel/IKernel.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            
                            interface IKernelEvents {
                                event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
                            }
                            
                            
                            // This should be an interface, but interfaces can't inherit yet :(
                            contract IKernel is IKernelEvents, IVaultRecoverable {
                                function acl() public view returns (IACL);
                                function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                            
                                function setApp(bytes32 namespace, bytes32 appId, address app) public;
                                function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
                            }
                            
                            // File: contracts/kernel/KernelConstants.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            contract KernelAppIds {
                                /* Hardcoded constants to save gas
                                bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
                                bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
                                bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
                                */
                                bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
                                bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
                                bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
                            }
                            
                            
                            contract KernelNamespaceConstants {
                                /* Hardcoded constants to save gas
                                bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
                                bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
                                bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
                                */
                                bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
                                bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
                                bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
                            }
                            
                            // File: contracts/kernel/KernelStorage.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            contract KernelStorage {
                                // namespace => app id => address
                                mapping (bytes32 => mapping (bytes32 => address)) public apps;
                                bytes32 public recoveryVaultAppId;
                            }
                            
                            // File: contracts/acl/ACLSyntaxSugar.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            contract ACLSyntaxSugar {
                                function arr() internal pure returns (uint256[]) {
                                    return new uint256[](0);
                                }
                            
                                function arr(bytes32 _a) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a));
                                }
                            
                                function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b));
                                }
                            
                                function arr(address _a) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a));
                                }
                            
                                function arr(address _a, address _b) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b));
                                }
                            
                                function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), _b, _c);
                                }
                            
                                function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), _b, _c, _d);
                                }
                            
                                function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b));
                                }
                            
                                function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b), _c, _d, _e);
                                }
                            
                                function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b), uint256(_c));
                                }
                            
                                function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b), uint256(_c));
                                }
                            
                                function arr(uint256 _a) internal pure returns (uint256[] r) {
                                    r = new uint256[](1);
                                    r[0] = _a;
                                }
                            
                                function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
                                    r = new uint256[](2);
                                    r[0] = _a;
                                    r[1] = _b;
                                }
                            
                                function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
                                    r = new uint256[](3);
                                    r[0] = _a;
                                    r[1] = _b;
                                    r[2] = _c;
                                }
                            
                                function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
                                    r = new uint256[](4);
                                    r[0] = _a;
                                    r[1] = _b;
                                    r[2] = _c;
                                    r[3] = _d;
                                }
                            
                                function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
                                    r = new uint256[](5);
                                    r[0] = _a;
                                    r[1] = _b;
                                    r[2] = _c;
                                    r[3] = _d;
                                    r[4] = _e;
                                }
                            }
                            
                            
                            contract ACLHelpers {
                                function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
                                    return uint8(_x >> (8 * 30));
                                }
                            
                                function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
                                    return uint8(_x >> (8 * 31));
                                }
                            
                                function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
                                    a = uint32(_x);
                                    b = uint32(_x >> (8 * 4));
                                    c = uint32(_x >> (8 * 8));
                                }
                            }
                            
                            // File: contracts/common/ConversionHelpers.sol
                            
                            pragma solidity ^0.4.24;
                            
                            
                            library ConversionHelpers {
                                string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
                            
                                function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
                                    // Force cast the uint256[] into a bytes array, by overwriting its length
                                    // Note that the bytes array doesn't need to be initialized as we immediately overwrite it
                                    // with the input and a new length. The input becomes invalid from this point forward.
                                    uint256 byteLength = _input.length * 32;
                                    assembly {
                                        output := _input
                                        mstore(output, byteLength)
                                    }
                                }
                            
                                function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
                                    // Force cast the bytes array into a uint256[], by overwriting its length
                                    // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
                                    // with the input and a new length. The input becomes invalid from this point forward.
                                    uint256 intsLength = _input.length / 32;
                                    require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
                            
                                    assembly {
                                        output := _input
                                        mstore(output, intsLength)
                                    }
                                }
                            }
                            
                            // File: contracts/common/IsContract.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            contract IsContract {
                                /*
                                * NOTE: this should NEVER be used for authentication
                                * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
                                *
                                * This is only intended to be used as a sanity check that an address is actually a contract,
                                * RATHER THAN an address not being a contract.
                                */
                                function isContract(address _target) internal view returns (bool) {
                                    if (_target == address(0)) {
                                        return false;
                                    }
                            
                                    uint256 size;
                                    assembly { size := extcodesize(_target) }
                                    return size > 0;
                                }
                            }
                            
                            // File: contracts/common/Uint256Helpers.sol
                            
                            pragma solidity ^0.4.24;
                            
                            
                            library Uint256Helpers {
                                uint256 private constant MAX_UINT64 = uint64(-1);
                            
                                string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
                            
                                function toUint64(uint256 a) internal pure returns (uint64) {
                                    require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
                                    return uint64(a);
                                }
                            }
                            
                            // File: contracts/common/TimeHelpers.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            contract TimeHelpers {
                                using Uint256Helpers for uint256;
                            
                                /**
                                * @dev Returns the current block number.
                                *      Using a function rather than `block.number` allows us to easily mock the block number in
                                *      tests.
                                */
                                function getBlockNumber() internal view returns (uint256) {
                                    return block.number;
                                }
                            
                                /**
                                * @dev Returns the current block number, converted to uint64.
                                *      Using a function rather than `block.number` allows us to easily mock the block number in
                                *      tests.
                                */
                                function getBlockNumber64() internal view returns (uint64) {
                                    return getBlockNumber().toUint64();
                                }
                            
                                /**
                                * @dev Returns the current timestamp.
                                *      Using a function rather than `block.timestamp` allows us to easily mock it in
                                *      tests.
                                */
                                function getTimestamp() internal view returns (uint256) {
                                    return block.timestamp; // solium-disable-line security/no-block-members
                                }
                            
                                /**
                                * @dev Returns the current timestamp, converted to uint64.
                                *      Using a function rather than `block.timestamp` allows us to easily mock it in
                                *      tests.
                                */
                                function getTimestamp64() internal view returns (uint64) {
                                    return getTimestamp().toUint64();
                                }
                            }
                            
                            // File: contracts/common/UnstructuredStorage.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            library UnstructuredStorage {
                                function getStorageBool(bytes32 position) internal view returns (bool data) {
                                    assembly { data := sload(position) }
                                }
                            
                                function getStorageAddress(bytes32 position) internal view returns (address data) {
                                    assembly { data := sload(position) }
                                }
                            
                                function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
                                    assembly { data := sload(position) }
                                }
                            
                                function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
                                    assembly { data := sload(position) }
                                }
                            
                                function setStorageBool(bytes32 position, bool data) internal {
                                    assembly { sstore(position, data) }
                                }
                            
                                function setStorageAddress(bytes32 position, address data) internal {
                                    assembly { sstore(position, data) }
                                }
                            
                                function setStorageBytes32(bytes32 position, bytes32 data) internal {
                                    assembly { sstore(position, data) }
                                }
                            
                                function setStorageUint256(bytes32 position, uint256 data) internal {
                                    assembly { sstore(position, data) }
                                }
                            }
                            
                            // File: contracts/common/Initializable.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            
                            contract Initializable is TimeHelpers {
                                using UnstructuredStorage for bytes32;
                            
                                // keccak256("aragonOS.initializable.initializationBlock")
                                bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
                            
                                string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
                                string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
                            
                                modifier onlyInit {
                                    require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
                                    _;
                                }
                            
                                modifier isInitialized {
                                    require(hasInitialized(), ERROR_NOT_INITIALIZED);
                                    _;
                                }
                            
                                /**
                                * @return Block number in which the contract was initialized
                                */
                                function getInitializationBlock() public view returns (uint256) {
                                    return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
                                }
                            
                                /**
                                * @return Whether the contract has been initialized by the time of the current block
                                */
                                function hasInitialized() public view returns (bool) {
                                    uint256 initializationBlock = getInitializationBlock();
                                    return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
                                }
                            
                                /**
                                * @dev Function to be called by top level contract after initialization has finished.
                                */
                                function initialized() internal onlyInit {
                                    INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
                                }
                            
                                /**
                                * @dev Function to be called by top level contract after initialization to enable the contract
                                *      at a future block number rather than immediately.
                                */
                                function initializedAt(uint256 _blockNumber) internal onlyInit {
                                    INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
                                }
                            }
                            
                            // File: contracts/common/Petrifiable.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            contract Petrifiable is Initializable {
                                // Use block UINT256_MAX (which should be never) as the initializable date
                                uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
                            
                                function isPetrified() public view returns (bool) {
                                    return getInitializationBlock() == PETRIFIED_BLOCK;
                                }
                            
                                /**
                                * @dev Function to be called by top level contract to prevent being initialized.
                                *      Useful for freezing base contracts when they're used behind proxies.
                                */
                                function petrify() internal onlyInit {
                                    initializedAt(PETRIFIED_BLOCK);
                                }
                            }
                            
                            // File: contracts/lib/token/ERC20.sol
                            
                            // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
                            
                            pragma solidity ^0.4.24;
                            
                            
                            /**
                             * @title ERC20 interface
                             * @dev see https://github.com/ethereum/EIPs/issues/20
                             */
                            contract ERC20 {
                                function totalSupply() public view returns (uint256);
                            
                                function balanceOf(address _who) public view returns (uint256);
                            
                                function allowance(address _owner, address _spender)
                                    public view returns (uint256);
                            
                                function transfer(address _to, uint256 _value) public returns (bool);
                            
                                function approve(address _spender, uint256 _value)
                                    public returns (bool);
                            
                                function transferFrom(address _from, address _to, uint256 _value)
                                    public returns (bool);
                            
                                event Transfer(
                                    address indexed from,
                                    address indexed to,
                                    uint256 value
                                );
                            
                                event Approval(
                                    address indexed owner,
                                    address indexed spender,
                                    uint256 value
                                );
                            }
                            
                            // File: contracts/common/EtherTokenConstant.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            // aragonOS and aragon-apps rely on address(0) to denote native ETH, in
                            // contracts where both tokens and ETH are accepted
                            contract EtherTokenConstant {
                                address internal constant ETH = address(0);
                            }
                            
                            // File: contracts/common/SafeERC20.sol
                            
                            // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
                            // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            library SafeERC20 {
                                // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
                                // https://github.com/ethereum/solidity/issues/3544
                                bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
                            
                                string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
                                string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
                            
                                function invokeAndCheckSuccess(address _addr, bytes memory _calldata)
                                    private
                                    returns (bool)
                                {
                                    bool ret;
                                    assembly {
                                        let ptr := mload(0x40)    // free memory pointer
                            
                                        let success := call(
                                            gas,                  // forward all gas
                                            _addr,                // address
                                            0,                    // no value
                                            add(_calldata, 0x20), // calldata start
                                            mload(_calldata),     // calldata length
                                            ptr,                  // write output over free memory
                                            0x20                  // uint256 return
                                        )
                            
                                        if gt(success, 0) {
                                            // Check number of bytes returned from last function call
                                            switch returndatasize
                            
                                            // No bytes returned: assume success
                                            case 0 {
                                                ret := 1
                                            }
                            
                                            // 32 bytes returned: check if non-zero
                                            case 0x20 {
                                                // Only return success if returned data was true
                                                // Already have output in ptr
                                                ret := eq(mload(ptr), 1)
                                            }
                            
                                            // Not sure what was returned: don't mark as success
                                            default { }
                                        }
                                    }
                                    return ret;
                                }
                            
                                function staticInvoke(address _addr, bytes memory _calldata)
                                    private
                                    view
                                    returns (bool, uint256)
                                {
                                    bool success;
                                    uint256 ret;
                                    assembly {
                                        let ptr := mload(0x40)    // free memory pointer
                            
                                        success := staticcall(
                                            gas,                  // forward all gas
                                            _addr,                // address
                                            add(_calldata, 0x20), // calldata start
                                            mload(_calldata),     // calldata length
                                            ptr,                  // write output over free memory
                                            0x20                  // uint256 return
                                        )
                            
                                        if gt(success, 0) {
                                            ret := mload(ptr)
                                        }
                                    }
                                    return (success, ret);
                                }
                            
                                /**
                                * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
                                *      Note that this makes an external call to the token.
                                */
                                function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
                                    bytes memory transferCallData = abi.encodeWithSelector(
                                        TRANSFER_SELECTOR,
                                        _to,
                                        _amount
                                    );
                                    return invokeAndCheckSuccess(_token, transferCallData);
                                }
                            
                                /**
                                * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
                                *      Note that this makes an external call to the token.
                                */
                                function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
                                    bytes memory transferFromCallData = abi.encodeWithSelector(
                                        _token.transferFrom.selector,
                                        _from,
                                        _to,
                                        _amount
                                    );
                                    return invokeAndCheckSuccess(_token, transferFromCallData);
                                }
                            
                                /**
                                * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
                                *      Note that this makes an external call to the token.
                                */
                                function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
                                    bytes memory approveCallData = abi.encodeWithSelector(
                                        _token.approve.selector,
                                        _spender,
                                        _amount
                                    );
                                    return invokeAndCheckSuccess(_token, approveCallData);
                                }
                            
                                /**
                                * @dev Static call into ERC20.balanceOf().
                                * Reverts if the call fails for some reason (should never fail).
                                */
                                function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
                                    bytes memory balanceOfCallData = abi.encodeWithSelector(
                                        _token.balanceOf.selector,
                                        _owner
                                    );
                            
                                    (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
                                    require(success, ERROR_TOKEN_BALANCE_REVERTED);
                            
                                    return tokenBalance;
                                }
                            
                                /**
                                * @dev Static call into ERC20.allowance().
                                * Reverts if the call fails for some reason (should never fail).
                                */
                                function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
                                    bytes memory allowanceCallData = abi.encodeWithSelector(
                                        _token.allowance.selector,
                                        _owner,
                                        _spender
                                    );
                            
                                    (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
                                    require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
                            
                                    return allowance;
                                }
                            
                                /**
                                * @dev Static call into ERC20.totalSupply().
                                * Reverts if the call fails for some reason (should never fail).
                                */
                                function staticTotalSupply(ERC20 _token) internal view returns (uint256) {
                                    bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector);
                            
                                    (bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData);
                                    require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
                            
                                    return totalSupply;
                                }
                            }
                            
                            // File: contracts/common/VaultRecoverable.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            
                            
                            
                            
                            contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
                                using SafeERC20 for ERC20;
                            
                                string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
                                string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
                                string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
                            
                                /**
                                 * @notice Send funds to recovery Vault. This contract should never receive funds,
                                 *         but in case it does, this function allows one to recover them.
                                 * @param _token Token balance to be sent to recovery vault.
                                 */
                                function transferToVault(address _token) external {
                                    require(allowRecoverability(_token), ERROR_DISALLOWED);
                                    address vault = getRecoveryVault();
                                    require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
                            
                                    uint256 balance;
                                    if (_token == ETH) {
                                        balance = address(this).balance;
                                        vault.transfer(balance);
                                    } else {
                                        ERC20 token = ERC20(_token);
                                        balance = token.staticBalanceOf(this);
                                        require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
                                    }
                            
                                    emit RecoverToVault(vault, _token, balance);
                                }
                            
                                /**
                                * @dev By default deriving from AragonApp makes it recoverable
                                * @param token Token address that would be recovered
                                * @return bool whether the app allows the recovery
                                */
                                function allowRecoverability(address token) public view returns (bool) {
                                    return true;
                                }
                            
                                // Cast non-implemented interface to be public so we can use it internally
                                function getRecoveryVault() public view returns (address);
                            }
                            
                            // File: contracts/apps/AppStorage.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            
                            contract AppStorage {
                                using UnstructuredStorage for bytes32;
                            
                                /* Hardcoded constants to save gas
                                bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
                                bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
                                */
                                bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
                                bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
                            
                                function kernel() public view returns (IKernel) {
                                    return IKernel(KERNEL_POSITION.getStorageAddress());
                                }
                            
                                function appId() public view returns (bytes32) {
                                    return APP_ID_POSITION.getStorageBytes32();
                                }
                            
                                function setKernel(IKernel _kernel) internal {
                                    KERNEL_POSITION.setStorageAddress(address(_kernel));
                                }
                            
                                function setAppId(bytes32 _appId) internal {
                                    APP_ID_POSITION.setStorageBytes32(_appId);
                                }
                            }
                            
                            // File: contracts/lib/misc/ERCProxy.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            contract ERCProxy {
                                uint256 internal constant FORWARDING = 1;
                                uint256 internal constant UPGRADEABLE = 2;
                            
                                function proxyType() public pure returns (uint256 proxyTypeId);
                                function implementation() public view returns (address codeAddr);
                            }
                            
                            // File: contracts/common/DelegateProxy.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            contract DelegateProxy is ERCProxy, IsContract {
                                uint256 internal constant FWD_GAS_LIMIT = 10000;
                            
                                /**
                                * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!)
                                * @param _dst Destination address to perform the delegatecall
                                * @param _calldata Calldata for the delegatecall
                                */
                                function delegatedFwd(address _dst, bytes _calldata) internal {
                                    require(isContract(_dst));
                                    uint256 fwdGasLimit = FWD_GAS_LIMIT;
                            
                                    assembly {
                                        let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
                                        let size := returndatasize
                                        let ptr := mload(0x40)
                                        returndatacopy(ptr, 0, size)
                            
                                        // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
                                        // if the call returned error data, forward it
                                        switch result case 0 { revert(ptr, size) }
                                        default { return(ptr, size) }
                                    }
                                }
                            }
                            
                            // File: contracts/common/DepositableStorage.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            contract DepositableStorage {
                                using UnstructuredStorage for bytes32;
                            
                                // keccak256("aragonOS.depositableStorage.depositable")
                                bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea;
                            
                                function isDepositable() public view returns (bool) {
                                    return DEPOSITABLE_POSITION.getStorageBool();
                                }
                            
                                function setDepositable(bool _depositable) internal {
                                    DEPOSITABLE_POSITION.setStorageBool(_depositable);
                                }
                            }
                            
                            // File: contracts/common/DepositableDelegateProxy.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            contract DepositableDelegateProxy is DepositableStorage, DelegateProxy {
                                event ProxyDeposit(address sender, uint256 value);
                            
                                function () external payable {
                                    uint256 forwardGasThreshold = FWD_GAS_LIMIT;
                                    bytes32 isDepositablePosition = DEPOSITABLE_POSITION;
                            
                                    // Optimized assembly implementation to prevent EIP-1884 from breaking deposits, reference code in Solidity:
                                    // https://github.com/aragon/aragonOS/blob/v4.2.1/contracts/common/DepositableDelegateProxy.sol#L10-L20
                                    assembly {
                                        // Continue only if the gas left is lower than the threshold for forwarding to the implementation code,
                                        // otherwise continue outside of the assembly block.
                                        if lt(gas, forwardGasThreshold) {
                                            // Only accept the deposit and emit an event if all of the following are true:
                                            // the proxy accepts deposits (isDepositable), msg.data.length == 0, and msg.value > 0
                                            if and(and(sload(isDepositablePosition), iszero(calldatasize)), gt(callvalue, 0)) {
                                                // Equivalent Solidity code for emitting the event:
                                                // emit ProxyDeposit(msg.sender, msg.value);
                            
                                                let logData := mload(0x40) // free memory pointer
                                                mstore(logData, caller) // add 'msg.sender' to the log data (first event param)
                                                mstore(add(logData, 0x20), callvalue) // add 'msg.value' to the log data (second event param)
                            
                                                // Emit an event with one topic to identify the event: keccak256('ProxyDeposit(address,uint256)') = 0x15ee...dee1
                                                log1(logData, 0x40, 0x15eeaa57c7bd188c1388020bcadc2c436ec60d647d36ef5b9eb3c742217ddee1)
                            
                                                stop() // Stop. Exits execution context
                                            }
                            
                                            // If any of above checks failed, revert the execution (if ETH was sent, it is returned to the sender)
                                            revert(0, 0)
                                        }
                                    }
                            
                                    address target = implementation();
                                    delegatedFwd(target, msg.data);
                                }
                            }
                            
                            // File: contracts/apps/AppProxyBase.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            
                            
                            contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants {
                                /**
                                * @dev Initialize AppProxy
                                * @param _kernel Reference to organization kernel for the app
                                * @param _appId Identifier for app
                                * @param _initializePayload Payload for call to be made after setup to initialize
                                */
                                constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public {
                                    setKernel(_kernel);
                                    setAppId(_appId);
                            
                                    // Implicit check that kernel is actually a Kernel
                                    // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to
                                    // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on
                                    // it.
                                    address appCode = getAppBase(_appId);
                            
                                    // If initialize payload is provided, it will be executed
                                    if (_initializePayload.length > 0) {
                                        require(isContract(appCode));
                                        // Cannot make delegatecall as a delegateproxy.delegatedFwd as it
                                        // returns ending execution context and halts contract deployment
                                        require(appCode.delegatecall(_initializePayload));
                                    }
                                }
                            
                                function getAppBase(bytes32 _appId) internal view returns (address) {
                                    return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId);
                                }
                            }
                            
                            // File: contracts/apps/AppProxyUpgradeable.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            contract AppProxyUpgradeable is AppProxyBase {
                                /**
                                * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app)
                                * @param _kernel Reference to organization kernel for the app
                                * @param _appId Identifier for app
                                * @param _initializePayload Payload for call to be made after setup to initialize
                                */
                                constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
                                    AppProxyBase(_kernel, _appId, _initializePayload)
                                    public // solium-disable-line visibility-first
                                {
                                    // solium-disable-previous-line no-empty-blocks
                                }
                            
                                /**
                                 * @dev ERC897, the address the proxy would delegate calls to
                                 */
                                function implementation() public view returns (address) {
                                    return getAppBase(appId());
                                }
                            
                                /**
                                 * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
                                 */
                                function proxyType() public pure returns (uint256 proxyTypeId) {
                                    return UPGRADEABLE;
                                }
                            }
                            
                            // File: contracts/apps/AppProxyPinned.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            
                            contract AppProxyPinned is IsContract, AppProxyBase {
                                using UnstructuredStorage for bytes32;
                            
                                // keccak256("aragonOS.appStorage.pinnedCode")
                                bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e;
                            
                                /**
                                * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app)
                                * @param _kernel Reference to organization kernel for the app
                                * @param _appId Identifier for app
                                * @param _initializePayload Payload for call to be made after setup to initialize
                                */
                                constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
                                    AppProxyBase(_kernel, _appId, _initializePayload)
                                    public // solium-disable-line visibility-first
                                {
                                    setPinnedCode(getAppBase(_appId));
                                    require(isContract(pinnedCode()));
                                }
                            
                                /**
                                 * @dev ERC897, the address the proxy would delegate calls to
                                 */
                                function implementation() public view returns (address) {
                                    return pinnedCode();
                                }
                            
                                /**
                                 * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
                                 */
                                function proxyType() public pure returns (uint256 proxyTypeId) {
                                    return FORWARDING;
                                }
                            
                                function setPinnedCode(address _pinnedCode) internal {
                                    PINNED_CODE_POSITION.setStorageAddress(_pinnedCode);
                                }
                            
                                function pinnedCode() internal view returns (address) {
                                    return PINNED_CODE_POSITION.getStorageAddress();
                                }
                            }
                            
                            // File: contracts/factory/AppProxyFactory.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            contract AppProxyFactory {
                                event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId);
                            
                                /**
                                * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId`
                                * @param _kernel App's Kernel reference
                                * @param _appId Identifier for app
                                * @return AppProxyUpgradeable
                                */
                                function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) {
                                    return newAppProxy(_kernel, _appId, new bytes(0));
                                }
                            
                                /**
                                * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
                                * @param _kernel App's Kernel reference
                                * @param _appId Identifier for app
                                * @return AppProxyUpgradeable
                                */
                                function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) {
                                    AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload);
                                    emit NewAppProxy(address(proxy), true, _appId);
                                    return proxy;
                                }
                            
                                /**
                                * @notice Create a new pinned app instance on `_kernel` with identifier `_appId`
                                * @param _kernel App's Kernel reference
                                * @param _appId Identifier for app
                                * @return AppProxyPinned
                                */
                                function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) {
                                    return newAppProxyPinned(_kernel, _appId, new bytes(0));
                                }
                            
                                /**
                                * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
                                * @param _kernel App's Kernel reference
                                * @param _appId Identifier for app
                                * @param _initializePayload Proxy initialization payload
                                * @return AppProxyPinned
                                */
                                function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) {
                                    AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload);
                                    emit NewAppProxy(address(proxy), false, _appId);
                                    return proxy;
                                }
                            }
                            
                            // File: contracts/kernel/Kernel.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            // solium-disable-next-line max-len
                            contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar {
                                /* Hardcoded constants to save gas
                                bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE");
                                */
                                bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0;
                            
                                string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT";
                                string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE";
                                string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED";
                            
                                /**
                                * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately.
                                * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized
                                */
                                constructor(bool _shouldPetrify) public {
                                    if (_shouldPetrify) {
                                        petrify();
                                    }
                                }
                            
                                /**
                                * @dev Initialize can only be called once. It saves the block number in which it was initialized.
                                * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions
                                * @param _baseAcl Address of base ACL app
                                * @param _permissionsCreator Entity that will be given permission over createPermission
                                */
                                function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit {
                                    initialized();
                            
                                    // Set ACL base
                                    _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl);
                            
                                    // Create ACL instance and attach it as the default ACL app
                                    IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID));
                                    acl.initialize(_permissionsCreator);
                                    _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl);
                            
                                    recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID;
                                }
                            
                                /**
                                * @dev Create a new instance of an app linked to this kernel
                                * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`
                                * @param _appId Identifier for app
                                * @param _appBase Address of the app's base implementation
                                * @return AppProxy instance
                                */
                                function newAppInstance(bytes32 _appId, address _appBase)
                                    public
                                    auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                                    returns (ERCProxy appProxy)
                                {
                                    return newAppInstance(_appId, _appBase, new bytes(0), false);
                                }
                            
                                /**
                                * @dev Create a new instance of an app linked to this kernel and set its base
                                *      implementation if it was not already set
                                * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
                                * @param _appId Identifier for app
                                * @param _appBase Address of the app's base implementation
                                * @param _initializePayload Payload for call made by the proxy during its construction to initialize
                                * @param _setDefault Whether the app proxy app is the default one.
                                *        Useful when the Kernel needs to know of an instance of a particular app,
                                *        like Vault for escape hatch mechanism.
                                * @return AppProxy instance
                                */
                                function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
                                    public
                                    auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                                    returns (ERCProxy appProxy)
                                {
                                    _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
                                    appProxy = newAppProxy(this, _appId, _initializePayload);
                                    // By calling setApp directly and not the internal functions, we make sure the params are checked
                                    // and it will only succeed if sender has permissions to set something to the namespace.
                                    if (_setDefault) {
                                        setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
                                    }
                                }
                            
                                /**
                                * @dev Create a new pinned instance of an app linked to this kernel
                                * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`.
                                * @param _appId Identifier for app
                                * @param _appBase Address of the app's base implementation
                                * @return AppProxy instance
                                */
                                function newPinnedAppInstance(bytes32 _appId, address _appBase)
                                    public
                                    auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                                    returns (ERCProxy appProxy)
                                {
                                    return newPinnedAppInstance(_appId, _appBase, new bytes(0), false);
                                }
                            
                                /**
                                * @dev Create a new pinned instance of an app linked to this kernel and set
                                *      its base implementation if it was not already set
                                * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
                                * @param _appId Identifier for app
                                * @param _appBase Address of the app's base implementation
                                * @param _initializePayload Payload for call made by the proxy during its construction to initialize
                                * @param _setDefault Whether the app proxy app is the default one.
                                *        Useful when the Kernel needs to know of an instance of a particular app,
                                *        like Vault for escape hatch mechanism.
                                * @return AppProxy instance
                                */
                                function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
                                    public
                                    auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                                    returns (ERCProxy appProxy)
                                {
                                    _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
                                    appProxy = newAppProxyPinned(this, _appId, _initializePayload);
                                    // By calling setApp directly and not the internal functions, we make sure the params are checked
                                    // and it will only succeed if sender has permissions to set something to the namespace.
                                    if (_setDefault) {
                                        setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
                                    }
                                }
                            
                                /**
                                * @dev Set the resolving address of an app instance or base implementation
                                * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app`
                                * @param _namespace App namespace to use
                                * @param _appId Identifier for app
                                * @param _app Address of the app instance or base implementation
                                * @return ID of app
                                */
                                function setApp(bytes32 _namespace, bytes32 _appId, address _app)
                                    public
                                    auth(APP_MANAGER_ROLE, arr(_namespace, _appId))
                                {
                                    _setApp(_namespace, _appId, _app);
                                }
                            
                                /**
                                * @dev Set the default vault id for the escape hatch mechanism
                                * @param _recoveryVaultAppId Identifier of the recovery vault app
                                */
                                function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId)
                                    public
                                    auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId))
                                {
                                    recoveryVaultAppId = _recoveryVaultAppId;
                                }
                            
                                // External access to default app id and namespace constants to mimic default getters for constants
                                /* solium-disable function-order, mixedcase */
                                function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; }
                                function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; }
                                function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; }
                                function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; }
                                function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; }
                                /* solium-enable function-order, mixedcase */
                            
                                /**
                                * @dev Get the address of an app instance or base implementation
                                * @param _namespace App namespace to use
                                * @param _appId Identifier for app
                                * @return Address of the app
                                */
                                function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) {
                                    return apps[_namespace][_appId];
                                }
                            
                                /**
                                * @dev Get the address of the recovery Vault instance (to recover funds)
                                * @return Address of the Vault
                                */
                                function getRecoveryVault() public view returns (address) {
                                    return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId];
                                }
                            
                                /**
                                * @dev Get the installed ACL app
                                * @return ACL app
                                */
                                function acl() public view returns (IACL) {
                                    return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID));
                                }
                            
                                /**
                                * @dev Function called by apps to check ACL on kernel or to check permission status
                                * @param _who Sender of the original call
                                * @param _where Address of the app
                                * @param _what Identifier for a group of actions in app
                                * @param _how Extra data for ACL auth
                                * @return Boolean indicating whether the ACL allows the role or not.
                                *         Always returns false if the kernel hasn't been initialized yet.
                                */
                                function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) {
                                    IACL defaultAcl = acl();
                                    return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas)
                                        defaultAcl.hasPermission(_who, _where, _what, _how);
                                }
                            
                                function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal {
                                    require(isContract(_app), ERROR_APP_NOT_CONTRACT);
                                    apps[_namespace][_appId] = _app;
                                    emit SetApp(_namespace, _appId, _app);
                                }
                            
                                function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal {
                                    address app = getApp(_namespace, _appId);
                                    if (app != address(0)) {
                                        // The only way to set an app is if it passes the isContract check, so no need to check it again
                                        require(app == _app, ERROR_INVALID_APP_CHANGE);
                                    } else {
                                        _setApp(_namespace, _appId, _app);
                                    }
                                }
                            
                                modifier auth(bytes32 _role, uint256[] memory _params) {
                                    require(
                                        hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)),
                                        ERROR_AUTH_FAILED
                                    );
                                    _;
                                }
                            }
                            
                            // File: contracts/kernel/KernelProxy.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            
                            
                            
                            contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy {
                                /**
                                * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation
                                *      can update the reference, which effectively upgrades the contract
                                * @param _kernelImpl Address of the contract used as implementation for kernel
                                */
                                constructor(IKernel _kernelImpl) public {
                                    require(isContract(address(_kernelImpl)));
                                    apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl;
                            
                                    // Note that emitting this event is important for verifying that a KernelProxy instance
                                    // was never upgraded to a malicious Kernel logic contract over its lifespan.
                                    // This starts the "chain of trust", that can be followed through later SetApp() events
                                    // emitted during kernel upgrades.
                                    emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl);
                                }
                            
                                /**
                                 * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
                                 */
                                function proxyType() public pure returns (uint256 proxyTypeId) {
                                    return UPGRADEABLE;
                                }
                            
                                /**
                                * @dev ERC897, the address the proxy would delegate calls to
                                */
                                function implementation() public view returns (address) {
                                    return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID];
                                }
                            }
                            
                            // File: contracts/common/Autopetrified.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            contract Autopetrified is Petrifiable {
                                constructor() public {
                                    // Immediately petrify base (non-proxy) instances of inherited contracts on deploy.
                                    // This renders them uninitializable (and unusable without a proxy).
                                    petrify();
                                }
                            }
                            
                            // File: contracts/common/ReentrancyGuard.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            contract ReentrancyGuard {
                                using UnstructuredStorage for bytes32;
                            
                                /* Hardcoded constants to save gas
                                bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex");
                                */
                                bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb;
                            
                                string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL";
                            
                                modifier nonReentrant() {
                                    // Ensure mutex is unlocked
                                    require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT);
                            
                                    // Lock mutex before function call
                                    REENTRANCY_MUTEX_POSITION.setStorageBool(true);
                            
                                    // Perform function call
                                    _;
                            
                                    // Unlock mutex after function call
                                    REENTRANCY_MUTEX_POSITION.setStorageBool(false);
                                }
                            }
                            
                            // File: contracts/evmscript/IEVMScriptExecutor.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            interface IEVMScriptExecutor {
                                function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes);
                                function executorType() external pure returns (bytes32);
                            }
                            
                            // File: contracts/evmscript/IEVMScriptRegistry.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            contract EVMScriptRegistryConstants {
                                /* Hardcoded constants to save gas
                                bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg");
                                */
                                bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61;
                            }
                            
                            
                            interface IEVMScriptRegistry {
                                function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id);
                                function disableScriptExecutor(uint256 executorId) external;
                            
                                // TODO: this should be external
                                // See https://github.com/ethereum/solidity/issues/4832
                                function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor);
                            }
                            
                            // File: contracts/evmscript/EVMScriptRunner.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            
                            
                            
                            
                            contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants {
                                string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE";
                                string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED";
                            
                                /* This is manually crafted in assembly
                                string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN";
                                */
                            
                                event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData);
                            
                                function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
                                    return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script));
                                }
                            
                                function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) {
                                    address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID);
                                    return IEVMScriptRegistry(registryAddr);
                                }
                            
                                function runScript(bytes _script, bytes _input, address[] _blacklist)
                                    internal
                                    isInitialized
                                    protectState
                                    returns (bytes)
                                {
                                    IEVMScriptExecutor executor = getEVMScriptExecutor(_script);
                                    require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE);
                            
                                    bytes4 sig = executor.execScript.selector;
                                    bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist);
                            
                                    bytes memory output;
                                    assembly {
                                        let success := delegatecall(
                                            gas,                // forward all gas
                                            executor,           // address
                                            add(data, 0x20),    // calldata start
                                            mload(data),        // calldata length
                                            0,                  // don't write output (we'll handle this ourselves)
                                            0                   // don't write output
                                        )
                            
                                        output := mload(0x40) // free mem ptr get
                            
                                        switch success
                                        case 0 {
                                            // If the call errored, forward its full error data
                                            returndatacopy(output, 0, returndatasize)
                                            revert(output, returndatasize)
                                        }
                                        default {
                                            switch gt(returndatasize, 0x3f)
                                            case 0 {
                                                // Need at least 0x40 bytes returned for properly ABI-encoded bytes values,
                                                // revert with "EVMRUN_EXECUTOR_INVALID_RETURN"
                                                // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in
                                                // this memory layout
                                                mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000)         // error identifier
                                                mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
                                                mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length
                                                mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason
                            
                                                revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
                                            }
                                            default {
                                                // Copy result
                                                //
                                                // Needs to perform an ABI decode for the expected `bytes` return type of
                                                // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as:
                                                //    [ position of the first dynamic length return value = 0x20 (32 bytes) ]
                                                //    [ output length (32 bytes) ]
                                                //    [ output content (N bytes) ]
                                                //
                                                // Perform the ABI decode by ignoring the first 32 bytes of the return data
                                                let copysize := sub(returndatasize, 0x20)
                                                returndatacopy(output, 0x20, copysize)
                            
                                                mstore(0x40, add(output, copysize)) // free mem ptr set
                                            }
                                        }
                                    }
                            
                                    emit ScriptResult(address(executor), _script, _input, output);
                            
                                    return output;
                                }
                            
                                modifier protectState {
                                    address preKernel = address(kernel());
                                    bytes32 preAppId = appId();
                                    _; // exec
                                    require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED);
                                    require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED);
                                }
                            }
                            
                            // File: contracts/apps/AragonApp.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so
                            // that they can never be initialized.
                            // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy.
                            // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but
                            // are included so that they are automatically usable by subclassing contracts
                            contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar {
                                string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED";
                            
                                modifier auth(bytes32 _role) {
                                    require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED);
                                    _;
                                }
                            
                                modifier authP(bytes32 _role, uint256[] _params) {
                                    require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED);
                                    _;
                                }
                            
                                /**
                                * @dev Check whether an action can be performed by a sender for a particular role on this app
                                * @param _sender Sender of the call
                                * @param _role Role on this app
                                * @param _params Permission params for the role
                                * @return Boolean indicating whether the sender has the permissions to perform the action.
                                *         Always returns false if the app hasn't been initialized yet.
                                */
                                function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) {
                                    if (!hasInitialized()) {
                                        return false;
                                    }
                            
                                    IKernel linkedKernel = kernel();
                                    if (address(linkedKernel) == address(0)) {
                                        return false;
                                    }
                            
                                    return linkedKernel.hasPermission(
                                        _sender,
                                        address(this),
                                        _role,
                                        ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)
                                    );
                                }
                            
                                /**
                                * @dev Get the recovery vault for the app
                                * @return Recovery vault address for the app
                                */
                                function getRecoveryVault() public view returns (address) {
                                    // Funds recovery via a vault is only available when used with a kernel
                                    return kernel().getRecoveryVault(); // if kernel is not set, it will revert
                                }
                            }
                            
                            // File: contracts/acl/IACLOracle.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            interface IACLOracle {
                                function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool);
                            }
                            
                            // File: contracts/acl/ACL.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            
                            
                            
                            
                            /* solium-disable function-order */
                            // Allow public initialize() to be first
                            contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers {
                                /* Hardcoded constants to save gas
                                bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE");
                                */
                                bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a;
                            
                                enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types
                            
                                struct Param {
                                    uint8 id;
                                    uint8 op;
                                    uint240 value; // even though value is an uint240 it can store addresses
                                    // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal
                                    // op and id take less than 1 byte each so it can be kept in 1 sstore
                                }
                            
                                uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200;
                                uint8 internal constant TIMESTAMP_PARAM_ID    = 201;
                                // 202 is unused
                                uint8 internal constant ORACLE_PARAM_ID       = 203;
                                uint8 internal constant LOGIC_OP_PARAM_ID     = 204;
                                uint8 internal constant PARAM_VALUE_PARAM_ID  = 205;
                                // TODO: Add execution times param type?
                            
                                /* Hardcoded constant to save gas
                                bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0));
                                */
                                bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563;
                                bytes32 public constant NO_PERMISSION = bytes32(0);
                                address public constant ANY_ENTITY = address(-1);
                                address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager"
                            
                                string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL";
                                string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER";
                                string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER";
                            
                                // Whether someone has a permission
                                mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash
                                mapping (bytes32 => Param[]) internal permissionParams; // params hash => params
                            
                                // Who is the manager of a permission
                                mapping (bytes32 => address) internal permissionManager;
                            
                                event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed);
                                event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash);
                                event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager);
                            
                                modifier onlyPermissionManager(address _app, bytes32 _role) {
                                    require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER);
                                    _;
                                }
                            
                                modifier noPermissionManager(address _app, bytes32 _role) {
                                    // only allow permission creation (or re-creation) when there is no manager
                                    require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER);
                                    _;
                                }
                            
                                /**
                                * @dev Initialize can only be called once. It saves the block number in which it was initialized.
                                * @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions
                                * @param _permissionsCreator Entity that will be given permission over createPermission
                                */
                                function initialize(address _permissionsCreator) public onlyInit {
                                    initialized();
                                    require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL);
                            
                                    _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator);
                                }
                            
                                /**
                                * @dev Creates a permission that wasn't previously set and managed.
                                *      If a created permission is removed it is possible to reset it with createPermission.
                                *      This is the **ONLY** way to create permissions and set managers to permissions that don't
                                *      have a manager.
                                *      In terms of the ACL being initialized, this function implicitly protects all the other
                                *      state-changing external functions, as they all require the sender to be a manager.
                                * @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager
                                * @param _entity Address of the whitelisted entity that will be able to perform the role
                                * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
                                * @param _role Identifier for the group of actions in app given access to perform
                                * @param _manager Address of the entity that will be able to grant and revoke the permission further.
                                */
                                function createPermission(address _entity, address _app, bytes32 _role, address _manager)
                                    external
                                    auth(CREATE_PERMISSIONS_ROLE)
                                    noPermissionManager(_app, _role)
                                {
                                    _createPermission(_entity, _app, _role, _manager);
                                }
                            
                                /**
                                * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager
                                * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
                                * @param _entity Address of the whitelisted entity that will be able to perform the role
                                * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
                                * @param _role Identifier for the group of actions in app given access to perform
                                */
                                function grantPermission(address _entity, address _app, bytes32 _role)
                                    external
                                {
                                    grantPermissionP(_entity, _app, _role, new uint256[](0));
                                }
                            
                                /**
                                * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager
                                * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
                                * @param _entity Address of the whitelisted entity that will be able to perform the role
                                * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
                                * @param _role Identifier for the group of actions in app given access to perform
                                * @param _params Permission parameters
                                */
                                function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params)
                                    public
                                    onlyPermissionManager(_app, _role)
                                {
                                    bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH;
                                    _setPermission(_entity, _app, _role, paramsHash);
                                }
                            
                                /**
                                * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager
                                * @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app`
                                * @param _entity Address of the whitelisted entity to revoke access from
                                * @param _app Address of the app in which the role will be revoked
                                * @param _role Identifier for the group of actions in app being revoked
                                */
                                function revokePermission(address _entity, address _app, bytes32 _role)
                                    external
                                    onlyPermissionManager(_app, _role)
                                {
                                    _setPermission(_entity, _app, _role, NO_PERMISSION);
                                }
                            
                                /**
                                * @notice Set `_newManager` as the manager of `_role` in `_app`
                                * @param _newManager Address for the new manager
                                * @param _app Address of the app in which the permission management is being transferred
                                * @param _role Identifier for the group of actions being transferred
                                */
                                function setPermissionManager(address _newManager, address _app, bytes32 _role)
                                    external
                                    onlyPermissionManager(_app, _role)
                                {
                                    _setPermissionManager(_newManager, _app, _role);
                                }
                            
                                /**
                                * @notice Remove the manager of `_role` in `_app`
                                * @param _app Address of the app in which the permission is being unmanaged
                                * @param _role Identifier for the group of actions being unmanaged
                                */
                                function removePermissionManager(address _app, bytes32 _role)
                                    external
                                    onlyPermissionManager(_app, _role)
                                {
                                    _setPermissionManager(address(0), _app, _role);
                                }
                            
                                /**
                                * @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
                                * @param _app Address of the app in which the permission is being burned
                                * @param _role Identifier for the group of actions being burned
                                */
                                function createBurnedPermission(address _app, bytes32 _role)
                                    external
                                    auth(CREATE_PERMISSIONS_ROLE)
                                    noPermissionManager(_app, _role)
                                {
                                    _setPermissionManager(BURN_ENTITY, _app, _role);
                                }
                            
                                /**
                                * @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
                                * @param _app Address of the app in which the permission is being burned
                                * @param _role Identifier for the group of actions being burned
                                */
                                function burnPermissionManager(address _app, bytes32 _role)
                                    external
                                    onlyPermissionManager(_app, _role)
                                {
                                    _setPermissionManager(BURN_ENTITY, _app, _role);
                                }
                            
                                /**
                                 * @notice Get parameters for permission array length
                                 * @param _entity Address of the whitelisted entity that will be able to perform the role
                                 * @param _app Address of the app
                                 * @param _role Identifier for a group of actions in app
                                 * @return Length of the array
                                 */
                                function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) {
                                    return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length;
                                }
                            
                                /**
                                * @notice Get parameter for permission
                                * @param _entity Address of the whitelisted entity that will be able to perform the role
                                * @param _app Address of the app
                                * @param _role Identifier for a group of actions in app
                                * @param _index Index of parameter in the array
                                * @return Parameter (id, op, value)
                                */
                                function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index)
                                    external
                                    view
                                    returns (uint8, uint8, uint240)
                                {
                                    Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index];
                                    return (param.id, param.op, param.value);
                                }
                            
                                /**
                                * @dev Get manager for permission
                                * @param _app Address of the app
                                * @param _role Identifier for a group of actions in app
                                * @return address of the manager for the permission
                                */
                                function getPermissionManager(address _app, bytes32 _role) public view returns (address) {
                                    return permissionManager[roleHash(_app, _role)];
                                }
                            
                                /**
                                * @dev Function called by apps to check ACL on kernel or to check permission statu
                                * @param _who Sender of the original call
                                * @param _where Address of the app
                                * @param _where Identifier for a group of actions in app
                                * @param _how Permission parameters
                                * @return boolean indicating whether the ACL allows the role or not
                                */
                                function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) {
                                    return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how));
                                }
                            
                                function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) {
                                    bytes32 whoParams = permissions[permissionHash(_who, _where, _what)];
                                    if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) {
                                        return true;
                                    }
                            
                                    bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)];
                                    if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) {
                                        return true;
                                    }
                            
                                    return false;
                                }
                            
                                function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) {
                                    uint256[] memory empty = new uint256[](0);
                                    return hasPermission(_who, _where, _what, empty);
                                }
                            
                                function evalParams(
                                    bytes32 _paramsHash,
                                    address _who,
                                    address _where,
                                    bytes32 _what,
                                    uint256[] _how
                                ) public view returns (bool)
                                {
                                    if (_paramsHash == EMPTY_PARAM_HASH) {
                                        return true;
                                    }
                            
                                    return _evalParam(_paramsHash, 0, _who, _where, _what, _how);
                                }
                            
                                /**
                                * @dev Internal createPermission for access inside the kernel (on instantiation)
                                */
                                function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal {
                                    _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH);
                                    _setPermissionManager(_manager, _app, _role);
                                }
                            
                                /**
                                * @dev Internal function called to actually save the permission
                                */
                                function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal {
                                    permissions[permissionHash(_entity, _app, _role)] = _paramsHash;
                                    bool entityHasPermission = _paramsHash != NO_PERMISSION;
                                    bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH;
                            
                                    emit SetPermission(_entity, _app, _role, entityHasPermission);
                                    if (permissionHasParams) {
                                        emit SetPermissionParams(_entity, _app, _role, _paramsHash);
                                    }
                                }
                            
                                function _saveParams(uint256[] _encodedParams) internal returns (bytes32) {
                                    bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams));
                                    Param[] storage params = permissionParams[paramHash];
                            
                                    if (params.length == 0) { // params not saved before
                                        for (uint256 i = 0; i < _encodedParams.length; i++) {
                                            uint256 encodedParam = _encodedParams[i];
                                            Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam));
                                            params.push(param);
                                        }
                                    }
                            
                                    return paramHash;
                                }
                            
                                function _evalParam(
                                    bytes32 _paramsHash,
                                    uint32 _paramId,
                                    address _who,
                                    address _where,
                                    bytes32 _what,
                                    uint256[] _how
                                ) internal view returns (bool)
                                {
                                    if (_paramId >= permissionParams[_paramsHash].length) {
                                        return false; // out of bounds
                                    }
                            
                                    Param memory param = permissionParams[_paramsHash][_paramId];
                            
                                    if (param.id == LOGIC_OP_PARAM_ID) {
                                        return _evalLogic(param, _paramsHash, _who, _where, _what, _how);
                                    }
                            
                                    uint256 value;
                                    uint256 comparedTo = uint256(param.value);
                            
                                    // get value
                                    if (param.id == ORACLE_PARAM_ID) {
                                        value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0;
                                        comparedTo = 1;
                                    } else if (param.id == BLOCK_NUMBER_PARAM_ID) {
                                        value = getBlockNumber();
                                    } else if (param.id == TIMESTAMP_PARAM_ID) {
                                        value = getTimestamp();
                                    } else if (param.id == PARAM_VALUE_PARAM_ID) {
                                        value = uint256(param.value);
                                    } else {
                                        if (param.id >= _how.length) {
                                            return false;
                                        }
                                        value = uint256(uint240(_how[param.id])); // force lost precision
                                    }
                            
                                    if (Op(param.op) == Op.RET) {
                                        return uint256(value) > 0;
                                    }
                            
                                    return compare(value, Op(param.op), comparedTo);
                                }
                            
                                function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how)
                                    internal
                                    view
                                    returns (bool)
                                {
                                    if (Op(_param.op) == Op.IF_ELSE) {
                                        uint32 conditionParam;
                                        uint32 successParam;
                                        uint32 failureParam;
                            
                                        (conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value));
                                        bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how);
                            
                                        return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how);
                                    }
                            
                                    uint32 param1;
                                    uint32 param2;
                            
                                    (param1, param2,) = decodeParamsList(uint256(_param.value));
                                    bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how);
                            
                                    if (Op(_param.op) == Op.NOT) {
                                        return !r1;
                                    }
                            
                                    if (r1 && Op(_param.op) == Op.OR) {
                                        return true;
                                    }
                            
                                    if (!r1 && Op(_param.op) == Op.AND) {
                                        return false;
                                    }
                            
                                    bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how);
                            
                                    if (Op(_param.op) == Op.XOR) {
                                        return r1 != r2;
                                    }
                            
                                    return r2; // both or and and depend on result of r2 after checks
                                }
                            
                                function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) {
                                    if (_op == Op.EQ)  return _a == _b;                              // solium-disable-line lbrace
                                    if (_op == Op.NEQ) return _a != _b;                              // solium-disable-line lbrace
                                    if (_op == Op.GT)  return _a > _b;                               // solium-disable-line lbrace
                                    if (_op == Op.LT)  return _a < _b;                               // solium-disable-line lbrace
                                    if (_op == Op.GTE) return _a >= _b;                              // solium-disable-line lbrace
                                    if (_op == Op.LTE) return _a <= _b;                              // solium-disable-line lbrace
                                    return false;
                                }
                            
                                function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) {
                                    bytes4 sig = _oracleAddr.canPerform.selector;
                            
                                    // a raw call is required so we can return false if the call reverts, rather than reverting
                                    bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how);
                            
                                    bool ok;
                                    assembly {
                                        // send all available gas; if the oracle eats up all the gas, we will eventually revert
                                        // note that we are currently guaranteed to still have some gas after the call from
                                        // EIP-150's 63/64 gas forward rule
                                        ok := staticcall(gas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0)
                                    }
                            
                                    if (!ok) {
                                        return false;
                                    }
                            
                                    uint256 size;
                                    assembly { size := returndatasize }
                                    if (size != 32) {
                                        return false;
                                    }
                            
                                    bool result;
                                    assembly {
                                        let ptr := mload(0x40)       // get next free memory ptr
                                        returndatacopy(ptr, 0, size) // copy return from above `staticcall`
                                        result := mload(ptr)         // read data at ptr and set it to result
                                        mstore(ptr, 0)               // set pointer memory to 0 so it still is the next free ptr
                                    }
                            
                                    return result;
                                }
                            
                                /**
                                * @dev Internal function that sets management
                                */
                                function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal {
                                    permissionManager[roleHash(_app, _role)] = _newManager;
                                    emit ChangePermissionManager(_app, _role, _newManager);
                                }
                            
                                function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) {
                                    return keccak256(abi.encodePacked("ROLE", _where, _what));
                                }
                            
                                function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) {
                                    return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what));
                                }
                            }
                            
                            // File: contracts/evmscript/ScriptHelpers.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            library ScriptHelpers {
                                function getSpecId(bytes _script) internal pure returns (uint32) {
                                    return uint32At(_script, 0);
                                }
                            
                                function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) {
                                    assembly {
                                        result := mload(add(_data, add(0x20, _location)))
                                    }
                                }
                            
                                function addressAt(bytes _data, uint256 _location) internal pure returns (address result) {
                                    uint256 word = uint256At(_data, _location);
                            
                                    assembly {
                                        result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000),
                                        0x1000000000000000000000000)
                                    }
                                }
                            
                                function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) {
                                    uint256 word = uint256At(_data, _location);
                            
                                    assembly {
                                        result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000),
                                        0x100000000000000000000000000000000000000000000000000000000)
                                    }
                                }
                            
                                function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) {
                                    assembly {
                                        result := add(_data, add(0x20, _location))
                                    }
                                }
                            
                                function toBytes(bytes4 _sig) internal pure returns (bytes) {
                                    bytes memory payload = new bytes(4);
                                    assembly { mstore(add(payload, 0x20), _sig) }
                                    return payload;
                                }
                            }
                            
                            // File: contracts/evmscript/EVMScriptRegistry.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            
                            
                            /* solium-disable function-order */
                            // Allow public initialize() to be first
                            contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp {
                                using ScriptHelpers for bytes;
                            
                                /* Hardcoded constants to save gas
                                bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE");
                                bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE");
                                */
                                bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2;
                                // WARN: Manager can censor all votes and the like happening in an org
                                bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3;
                            
                                uint256 internal constant SCRIPT_START_LOCATION = 4;
                            
                                string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR";
                                string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED";
                                string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED";
                                string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT";
                            
                                struct ExecutorEntry {
                                    IEVMScriptExecutor executor;
                                    bool enabled;
                                }
                            
                                uint256 private executorsNextIndex;
                                mapping (uint256 => ExecutorEntry) public executors;
                            
                                event EnableExecutor(uint256 indexed executorId, address indexed executorAddress);
                                event DisableExecutor(uint256 indexed executorId, address indexed executorAddress);
                            
                                modifier executorExists(uint256 _executorId) {
                                    require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR);
                                    _;
                                }
                            
                                /**
                                * @notice Initialize the registry
                                */
                                function initialize() public onlyInit {
                                    initialized();
                                    // Create empty record to begin executor IDs at 1
                                    executorsNextIndex = 1;
                                }
                            
                                /**
                                * @notice Add a new script executor with address `_executor` to the registry
                                * @param _executor Address of the IEVMScriptExecutor that will be added to the registry
                                * @return id Identifier of the executor in the registry
                                */
                                function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) {
                                    uint256 executorId = executorsNextIndex++;
                                    executors[executorId] = ExecutorEntry(_executor, true);
                                    emit EnableExecutor(executorId, _executor);
                                    return executorId;
                                }
                            
                                /**
                                * @notice Disable script executor with ID `_executorId`
                                * @param _executorId Identifier of the executor in the registry
                                */
                                function disableScriptExecutor(uint256 _executorId)
                                    external
                                    authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
                                {
                                    // Note that we don't need to check for an executor's existence in this case, as only
                                    // existing executors can be enabled
                                    ExecutorEntry storage executorEntry = executors[_executorId];
                                    require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED);
                                    executorEntry.enabled = false;
                                    emit DisableExecutor(_executorId, executorEntry.executor);
                                }
                            
                                /**
                                * @notice Enable script executor with ID `_executorId`
                                * @param _executorId Identifier of the executor in the registry
                                */
                                function enableScriptExecutor(uint256 _executorId)
                                    external
                                    authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
                                    executorExists(_executorId)
                                {
                                    ExecutorEntry storage executorEntry = executors[_executorId];
                                    require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED);
                                    executorEntry.enabled = true;
                                    emit EnableExecutor(_executorId, executorEntry.executor);
                                }
                            
                                /**
                                * @dev Get the script executor that can execute a particular script based on its first 4 bytes
                                * @param _script EVMScript being inspected
                                */
                                function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
                                    require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT);
                                    uint256 id = _script.getSpecId();
                            
                                    // Note that we don't need to check for an executor's existence in this case, as only
                                    // existing executors can be enabled
                                    ExecutorEntry storage entry = executors[id];
                                    return entry.enabled ? entry.executor : IEVMScriptExecutor(0);
                                }
                            }
                            
                            // File: contracts/evmscript/executors/BaseEVMScriptExecutor.sol
                            
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            
                            contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified {
                                uint256 internal constant SCRIPT_START_LOCATION = 4;
                            }
                            
                            // File: contracts/evmscript/executors/CallsScript.sol
                            
                            pragma solidity 0.4.24;
                            
                            // Inspired by https://github.com/reverendus/tx-manager
                            
                            
                            
                            
                            contract CallsScript is BaseEVMScriptExecutor {
                                using ScriptHelpers for bytes;
                            
                                /* Hardcoded constants to save gas
                                bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT");
                                */
                                bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302;
                            
                                string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL";
                                string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH";
                            
                                /* This is manually crafted in assembly
                                string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED";
                                */
                            
                                event LogScriptCall(address indexed sender, address indexed src, address indexed dst);
                            
                                /**
                                * @notice Executes a number of call scripts
                                * @param _script [ specId (uint32) ] many calls with this structure ->
                                *    [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ]
                                * @param _blacklist Addresses the script cannot call to, or will revert.
                                * @return Always returns empty byte array
                                */
                                function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) {
                                    uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id
                                    while (location < _script.length) {
                                        // Check there's at least address + calldataLength available
                                        require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH);
                            
                                        address contractAddress = _script.addressAt(location);
                                        // Check address being called is not blacklist
                                        for (uint256 i = 0; i < _blacklist.length; i++) {
                                            require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL);
                                        }
                            
                                        // logged before execution to ensure event ordering in receipt
                                        // if failed entire execution is reverted regardless
                                        emit LogScriptCall(msg.sender, address(this), contractAddress);
                            
                                        uint256 calldataLength = uint256(_script.uint32At(location + 0x14));
                                        uint256 startOffset = location + 0x14 + 0x04;
                                        uint256 calldataStart = _script.locationOf(startOffset);
                            
                                        // compute end of script / next location
                                        location = startOffset + calldataLength;
                                        require(location <= _script.length, ERROR_INVALID_LENGTH);
                            
                                        bool success;
                                        assembly {
                                            success := call(
                                                sub(gas, 5000),       // forward gas left - 5000
                                                contractAddress,      // address
                                                0,                    // no value
                                                calldataStart,        // calldata start
                                                calldataLength,       // calldata length
                                                0,                    // don't write output
                                                0                     // don't write output
                                            )
                            
                                            switch success
                                            case 0 {
                                                let ptr := mload(0x40)
                            
                                                switch returndatasize
                                                case 0 {
                                                    // No error data was returned, revert with "EVMCALLS_CALL_REVERTED"
                                                    // See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in
                                                    // this memory layout
                                                    mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000)         // error identifier
                                                    mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
                                                    mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length
                                                    mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason
                            
                                                    revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
                                                }
                                                default {
                                                    // Forward the full error data
                                                    returndatacopy(ptr, 0, returndatasize)
                                                    revert(ptr, returndatasize)
                                                }
                                            }
                                            default { }
                                        }
                                    }
                                    // No need to allocate empty bytes for the return as this can only be called via an delegatecall
                                    // (due to the isInitialized modifier)
                                }
                            
                                function executorType() external pure returns (bytes32) {
                                    return EXECUTOR_TYPE;
                                }
                            }
                            
                            // File: contracts/factory/EVMScriptRegistryFactory.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            
                            
                            
                            contract EVMScriptRegistryFactory is EVMScriptRegistryConstants {
                                EVMScriptRegistry public baseReg;
                                IEVMScriptExecutor public baseCallScript;
                            
                                /**
                                * @notice Create a new EVMScriptRegistryFactory.
                                */
                                constructor() public {
                                    baseReg = new EVMScriptRegistry();
                                    baseCallScript = IEVMScriptExecutor(new CallsScript());
                                }
                            
                                /**
                                * @notice Install a new pinned instance of EVMScriptRegistry on `_dao`.
                                * @param _dao Kernel
                                * @return Installed EVMScriptRegistry
                                */
                                function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) {
                                    bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector);
                                    reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true));
                            
                                    ACL acl = ACL(_dao.acl());
                            
                                    acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this);
                            
                                    reg.addScriptExecutor(baseCallScript);     // spec 1 = CallsScript
                            
                                    // Clean up the permissions
                                    acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
                                    acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
                            
                                    return reg;
                                }
                            }
                            
                            // File: contracts/factory/DAOFactory.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            
                            
                            
                            
                            contract DAOFactory {
                                IKernel public baseKernel;
                                IACL public baseACL;
                                EVMScriptRegistryFactory public regFactory;
                            
                                event DeployDAO(address dao);
                                event DeployEVMScriptRegistry(address reg);
                            
                                /**
                                * @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`.
                                * @param _baseKernel Base Kernel
                                * @param _baseACL Base ACL
                                * @param _regFactory EVMScriptRegistry factory
                                */
                                constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public {
                                    // No need to init as it cannot be killed by devops199
                                    if (address(_regFactory) != address(0)) {
                                        regFactory = _regFactory;
                                    }
                            
                                    baseKernel = _baseKernel;
                                    baseACL = _baseACL;
                                }
                            
                                /**
                                * @notice Create a new DAO with `_root` set as the initial admin
                                * @param _root Address that will be granted control to setup DAO permissions
                                * @return Newly created DAO
                                */
                                function newDAO(address _root) public returns (Kernel) {
                                    Kernel dao = Kernel(new KernelProxy(baseKernel));
                            
                                    if (address(regFactory) == address(0)) {
                                        dao.initialize(baseACL, _root);
                                    } else {
                                        dao.initialize(baseACL, this);
                            
                                        ACL acl = ACL(dao.acl());
                                        bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE();
                                        bytes32 appManagerRole = dao.APP_MANAGER_ROLE();
                            
                                        acl.grantPermission(regFactory, acl, permRole);
                            
                                        acl.createPermission(regFactory, dao, appManagerRole, this);
                            
                                        EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao);
                                        emit DeployEVMScriptRegistry(address(reg));
                            
                                        // Clean up permissions
                                        // First, completely reset the APP_MANAGER_ROLE
                                        acl.revokePermission(regFactory, dao, appManagerRole);
                                        acl.removePermissionManager(dao, appManagerRole);
                            
                                        // Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE
                                        acl.revokePermission(regFactory, acl, permRole);
                                        acl.revokePermission(this, acl, permRole);
                                        acl.grantPermission(_root, acl, permRole);
                                        acl.setPermissionManager(_root, acl, permRole);
                                    }
                            
                                    emit DeployDAO(address(dao));
                            
                                    return dao;
                                }
                            }

                            File 10 of 12: Kernel
                            // File: contracts/acl/IACL.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            interface IACL {
                                function initialize(address permissionsCreator) external;
                            
                                // TODO: this should be external
                                // See https://github.com/ethereum/solidity/issues/4832
                                function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                            }
                            
                            // File: contracts/common/IVaultRecoverable.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            interface IVaultRecoverable {
                                event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
                            
                                function transferToVault(address token) external;
                            
                                function allowRecoverability(address token) external view returns (bool);
                                function getRecoveryVault() external view returns (address);
                            }
                            
                            // File: contracts/kernel/IKernel.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            
                            interface IKernelEvents {
                                event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
                            }
                            
                            
                            // This should be an interface, but interfaces can't inherit yet :(
                            contract IKernel is IKernelEvents, IVaultRecoverable {
                                function acl() public view returns (IACL);
                                function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                            
                                function setApp(bytes32 namespace, bytes32 appId, address app) public;
                                function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
                            }
                            
                            // File: contracts/kernel/KernelConstants.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            contract KernelAppIds {
                                /* Hardcoded constants to save gas
                                bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
                                bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
                                bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
                                */
                                bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
                                bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
                                bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
                            }
                            
                            
                            contract KernelNamespaceConstants {
                                /* Hardcoded constants to save gas
                                bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
                                bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
                                bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
                                */
                                bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
                                bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
                                bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
                            }
                            
                            // File: contracts/kernel/KernelStorage.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            contract KernelStorage {
                                // namespace => app id => address
                                mapping (bytes32 => mapping (bytes32 => address)) public apps;
                                bytes32 public recoveryVaultAppId;
                            }
                            
                            // File: contracts/acl/ACLSyntaxSugar.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            contract ACLSyntaxSugar {
                                function arr() internal pure returns (uint256[]) {
                                    return new uint256[](0);
                                }
                            
                                function arr(bytes32 _a) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a));
                                }
                            
                                function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b));
                                }
                            
                                function arr(address _a) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a));
                                }
                            
                                function arr(address _a, address _b) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b));
                                }
                            
                                function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), _b, _c);
                                }
                            
                                function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), _b, _c, _d);
                                }
                            
                                function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b));
                                }
                            
                                function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b), _c, _d, _e);
                                }
                            
                                function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b), uint256(_c));
                                }
                            
                                function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b), uint256(_c));
                                }
                            
                                function arr(uint256 _a) internal pure returns (uint256[] r) {
                                    r = new uint256[](1);
                                    r[0] = _a;
                                }
                            
                                function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
                                    r = new uint256[](2);
                                    r[0] = _a;
                                    r[1] = _b;
                                }
                            
                                function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
                                    r = new uint256[](3);
                                    r[0] = _a;
                                    r[1] = _b;
                                    r[2] = _c;
                                }
                            
                                function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
                                    r = new uint256[](4);
                                    r[0] = _a;
                                    r[1] = _b;
                                    r[2] = _c;
                                    r[3] = _d;
                                }
                            
                                function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
                                    r = new uint256[](5);
                                    r[0] = _a;
                                    r[1] = _b;
                                    r[2] = _c;
                                    r[3] = _d;
                                    r[4] = _e;
                                }
                            }
                            
                            
                            contract ACLHelpers {
                                function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
                                    return uint8(_x >> (8 * 30));
                                }
                            
                                function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
                                    return uint8(_x >> (8 * 31));
                                }
                            
                                function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
                                    a = uint32(_x);
                                    b = uint32(_x >> (8 * 4));
                                    c = uint32(_x >> (8 * 8));
                                }
                            }
                            
                            // File: contracts/common/ConversionHelpers.sol
                            
                            pragma solidity ^0.4.24;
                            
                            
                            library ConversionHelpers {
                                string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
                            
                                function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
                                    // Force cast the uint256[] into a bytes array, by overwriting its length
                                    // Note that the bytes array doesn't need to be initialized as we immediately overwrite it
                                    // with the input and a new length. The input becomes invalid from this point forward.
                                    uint256 byteLength = _input.length * 32;
                                    assembly {
                                        output := _input
                                        mstore(output, byteLength)
                                    }
                                }
                            
                                function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
                                    // Force cast the bytes array into a uint256[], by overwriting its length
                                    // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
                                    // with the input and a new length. The input becomes invalid from this point forward.
                                    uint256 intsLength = _input.length / 32;
                                    require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
                            
                                    assembly {
                                        output := _input
                                        mstore(output, intsLength)
                                    }
                                }
                            }
                            
                            // File: contracts/common/IsContract.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            contract IsContract {
                                /*
                                * NOTE: this should NEVER be used for authentication
                                * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
                                *
                                * This is only intended to be used as a sanity check that an address is actually a contract,
                                * RATHER THAN an address not being a contract.
                                */
                                function isContract(address _target) internal view returns (bool) {
                                    if (_target == address(0)) {
                                        return false;
                                    }
                            
                                    uint256 size;
                                    assembly { size := extcodesize(_target) }
                                    return size > 0;
                                }
                            }
                            
                            // File: contracts/common/Uint256Helpers.sol
                            
                            pragma solidity ^0.4.24;
                            
                            
                            library Uint256Helpers {
                                uint256 private constant MAX_UINT64 = uint64(-1);
                            
                                string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
                            
                                function toUint64(uint256 a) internal pure returns (uint64) {
                                    require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
                                    return uint64(a);
                                }
                            }
                            
                            // File: contracts/common/TimeHelpers.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            contract TimeHelpers {
                                using Uint256Helpers for uint256;
                            
                                /**
                                * @dev Returns the current block number.
                                *      Using a function rather than `block.number` allows us to easily mock the block number in
                                *      tests.
                                */
                                function getBlockNumber() internal view returns (uint256) {
                                    return block.number;
                                }
                            
                                /**
                                * @dev Returns the current block number, converted to uint64.
                                *      Using a function rather than `block.number` allows us to easily mock the block number in
                                *      tests.
                                */
                                function getBlockNumber64() internal view returns (uint64) {
                                    return getBlockNumber().toUint64();
                                }
                            
                                /**
                                * @dev Returns the current timestamp.
                                *      Using a function rather than `block.timestamp` allows us to easily mock it in
                                *      tests.
                                */
                                function getTimestamp() internal view returns (uint256) {
                                    return block.timestamp; // solium-disable-line security/no-block-members
                                }
                            
                                /**
                                * @dev Returns the current timestamp, converted to uint64.
                                *      Using a function rather than `block.timestamp` allows us to easily mock it in
                                *      tests.
                                */
                                function getTimestamp64() internal view returns (uint64) {
                                    return getTimestamp().toUint64();
                                }
                            }
                            
                            // File: contracts/common/UnstructuredStorage.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            library UnstructuredStorage {
                                function getStorageBool(bytes32 position) internal view returns (bool data) {
                                    assembly { data := sload(position) }
                                }
                            
                                function getStorageAddress(bytes32 position) internal view returns (address data) {
                                    assembly { data := sload(position) }
                                }
                            
                                function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
                                    assembly { data := sload(position) }
                                }
                            
                                function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
                                    assembly { data := sload(position) }
                                }
                            
                                function setStorageBool(bytes32 position, bool data) internal {
                                    assembly { sstore(position, data) }
                                }
                            
                                function setStorageAddress(bytes32 position, address data) internal {
                                    assembly { sstore(position, data) }
                                }
                            
                                function setStorageBytes32(bytes32 position, bytes32 data) internal {
                                    assembly { sstore(position, data) }
                                }
                            
                                function setStorageUint256(bytes32 position, uint256 data) internal {
                                    assembly { sstore(position, data) }
                                }
                            }
                            
                            // File: contracts/common/Initializable.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            
                            contract Initializable is TimeHelpers {
                                using UnstructuredStorage for bytes32;
                            
                                // keccak256("aragonOS.initializable.initializationBlock")
                                bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
                            
                                string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
                                string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
                            
                                modifier onlyInit {
                                    require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
                                    _;
                                }
                            
                                modifier isInitialized {
                                    require(hasInitialized(), ERROR_NOT_INITIALIZED);
                                    _;
                                }
                            
                                /**
                                * @return Block number in which the contract was initialized
                                */
                                function getInitializationBlock() public view returns (uint256) {
                                    return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
                                }
                            
                                /**
                                * @return Whether the contract has been initialized by the time of the current block
                                */
                                function hasInitialized() public view returns (bool) {
                                    uint256 initializationBlock = getInitializationBlock();
                                    return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
                                }
                            
                                /**
                                * @dev Function to be called by top level contract after initialization has finished.
                                */
                                function initialized() internal onlyInit {
                                    INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
                                }
                            
                                /**
                                * @dev Function to be called by top level contract after initialization to enable the contract
                                *      at a future block number rather than immediately.
                                */
                                function initializedAt(uint256 _blockNumber) internal onlyInit {
                                    INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
                                }
                            }
                            
                            // File: contracts/common/Petrifiable.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            contract Petrifiable is Initializable {
                                // Use block UINT256_MAX (which should be never) as the initializable date
                                uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
                            
                                function isPetrified() public view returns (bool) {
                                    return getInitializationBlock() == PETRIFIED_BLOCK;
                                }
                            
                                /**
                                * @dev Function to be called by top level contract to prevent being initialized.
                                *      Useful for freezing base contracts when they're used behind proxies.
                                */
                                function petrify() internal onlyInit {
                                    initializedAt(PETRIFIED_BLOCK);
                                }
                            }
                            
                            // File: contracts/lib/token/ERC20.sol
                            
                            // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
                            
                            pragma solidity ^0.4.24;
                            
                            
                            /**
                             * @title ERC20 interface
                             * @dev see https://github.com/ethereum/EIPs/issues/20
                             */
                            contract ERC20 {
                                function totalSupply() public view returns (uint256);
                            
                                function balanceOf(address _who) public view returns (uint256);
                            
                                function allowance(address _owner, address _spender)
                                    public view returns (uint256);
                            
                                function transfer(address _to, uint256 _value) public returns (bool);
                            
                                function approve(address _spender, uint256 _value)
                                    public returns (bool);
                            
                                function transferFrom(address _from, address _to, uint256 _value)
                                    public returns (bool);
                            
                                event Transfer(
                                    address indexed from,
                                    address indexed to,
                                    uint256 value
                                );
                            
                                event Approval(
                                    address indexed owner,
                                    address indexed spender,
                                    uint256 value
                                );
                            }
                            
                            // File: contracts/common/EtherTokenConstant.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            // aragonOS and aragon-apps rely on address(0) to denote native ETH, in
                            // contracts where both tokens and ETH are accepted
                            contract EtherTokenConstant {
                                address internal constant ETH = address(0);
                            }
                            
                            // File: contracts/common/SafeERC20.sol
                            
                            // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
                            // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            library SafeERC20 {
                                // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
                                // https://github.com/ethereum/solidity/issues/3544
                                bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
                            
                                string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
                                string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
                            
                                function invokeAndCheckSuccess(address _addr, bytes memory _calldata)
                                    private
                                    returns (bool)
                                {
                                    bool ret;
                                    assembly {
                                        let ptr := mload(0x40)    // free memory pointer
                            
                                        let success := call(
                                            gas,                  // forward all gas
                                            _addr,                // address
                                            0,                    // no value
                                            add(_calldata, 0x20), // calldata start
                                            mload(_calldata),     // calldata length
                                            ptr,                  // write output over free memory
                                            0x20                  // uint256 return
                                        )
                            
                                        if gt(success, 0) {
                                            // Check number of bytes returned from last function call
                                            switch returndatasize
                            
                                            // No bytes returned: assume success
                                            case 0 {
                                                ret := 1
                                            }
                            
                                            // 32 bytes returned: check if non-zero
                                            case 0x20 {
                                                // Only return success if returned data was true
                                                // Already have output in ptr
                                                ret := eq(mload(ptr), 1)
                                            }
                            
                                            // Not sure what was returned: don't mark as success
                                            default { }
                                        }
                                    }
                                    return ret;
                                }
                            
                                function staticInvoke(address _addr, bytes memory _calldata)
                                    private
                                    view
                                    returns (bool, uint256)
                                {
                                    bool success;
                                    uint256 ret;
                                    assembly {
                                        let ptr := mload(0x40)    // free memory pointer
                            
                                        success := staticcall(
                                            gas,                  // forward all gas
                                            _addr,                // address
                                            add(_calldata, 0x20), // calldata start
                                            mload(_calldata),     // calldata length
                                            ptr,                  // write output over free memory
                                            0x20                  // uint256 return
                                        )
                            
                                        if gt(success, 0) {
                                            ret := mload(ptr)
                                        }
                                    }
                                    return (success, ret);
                                }
                            
                                /**
                                * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
                                *      Note that this makes an external call to the token.
                                */
                                function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
                                    bytes memory transferCallData = abi.encodeWithSelector(
                                        TRANSFER_SELECTOR,
                                        _to,
                                        _amount
                                    );
                                    return invokeAndCheckSuccess(_token, transferCallData);
                                }
                            
                                /**
                                * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
                                *      Note that this makes an external call to the token.
                                */
                                function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
                                    bytes memory transferFromCallData = abi.encodeWithSelector(
                                        _token.transferFrom.selector,
                                        _from,
                                        _to,
                                        _amount
                                    );
                                    return invokeAndCheckSuccess(_token, transferFromCallData);
                                }
                            
                                /**
                                * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
                                *      Note that this makes an external call to the token.
                                */
                                function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
                                    bytes memory approveCallData = abi.encodeWithSelector(
                                        _token.approve.selector,
                                        _spender,
                                        _amount
                                    );
                                    return invokeAndCheckSuccess(_token, approveCallData);
                                }
                            
                                /**
                                * @dev Static call into ERC20.balanceOf().
                                * Reverts if the call fails for some reason (should never fail).
                                */
                                function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
                                    bytes memory balanceOfCallData = abi.encodeWithSelector(
                                        _token.balanceOf.selector,
                                        _owner
                                    );
                            
                                    (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
                                    require(success, ERROR_TOKEN_BALANCE_REVERTED);
                            
                                    return tokenBalance;
                                }
                            
                                /**
                                * @dev Static call into ERC20.allowance().
                                * Reverts if the call fails for some reason (should never fail).
                                */
                                function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
                                    bytes memory allowanceCallData = abi.encodeWithSelector(
                                        _token.allowance.selector,
                                        _owner,
                                        _spender
                                    );
                            
                                    (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
                                    require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
                            
                                    return allowance;
                                }
                            
                                /**
                                * @dev Static call into ERC20.totalSupply().
                                * Reverts if the call fails for some reason (should never fail).
                                */
                                function staticTotalSupply(ERC20 _token) internal view returns (uint256) {
                                    bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector);
                            
                                    (bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData);
                                    require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
                            
                                    return totalSupply;
                                }
                            }
                            
                            // File: contracts/common/VaultRecoverable.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            
                            
                            
                            
                            contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
                                using SafeERC20 for ERC20;
                            
                                string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
                                string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
                                string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
                            
                                /**
                                 * @notice Send funds to recovery Vault. This contract should never receive funds,
                                 *         but in case it does, this function allows one to recover them.
                                 * @param _token Token balance to be sent to recovery vault.
                                 */
                                function transferToVault(address _token) external {
                                    require(allowRecoverability(_token), ERROR_DISALLOWED);
                                    address vault = getRecoveryVault();
                                    require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
                            
                                    uint256 balance;
                                    if (_token == ETH) {
                                        balance = address(this).balance;
                                        vault.transfer(balance);
                                    } else {
                                        ERC20 token = ERC20(_token);
                                        balance = token.staticBalanceOf(this);
                                        require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
                                    }
                            
                                    emit RecoverToVault(vault, _token, balance);
                                }
                            
                                /**
                                * @dev By default deriving from AragonApp makes it recoverable
                                * @param token Token address that would be recovered
                                * @return bool whether the app allows the recovery
                                */
                                function allowRecoverability(address token) public view returns (bool) {
                                    return true;
                                }
                            
                                // Cast non-implemented interface to be public so we can use it internally
                                function getRecoveryVault() public view returns (address);
                            }
                            
                            // File: contracts/apps/AppStorage.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            
                            
                            contract AppStorage {
                                using UnstructuredStorage for bytes32;
                            
                                /* Hardcoded constants to save gas
                                bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
                                bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
                                */
                                bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
                                bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
                            
                                function kernel() public view returns (IKernel) {
                                    return IKernel(KERNEL_POSITION.getStorageAddress());
                                }
                            
                                function appId() public view returns (bytes32) {
                                    return APP_ID_POSITION.getStorageBytes32();
                                }
                            
                                function setKernel(IKernel _kernel) internal {
                                    KERNEL_POSITION.setStorageAddress(address(_kernel));
                                }
                            
                                function setAppId(bytes32 _appId) internal {
                                    APP_ID_POSITION.setStorageBytes32(_appId);
                                }
                            }
                            
                            // File: contracts/lib/misc/ERCProxy.sol
                            
                            /*
                             * SPDX-License-Identitifer:    MIT
                             */
                            
                            pragma solidity ^0.4.24;
                            
                            
                            contract ERCProxy {
                                uint256 internal constant FORWARDING = 1;
                                uint256 internal constant UPGRADEABLE = 2;
                            
                                function proxyType() public pure returns (uint256 proxyTypeId);
                                function implementation() public view returns (address codeAddr);
                            }
                            
                            // File: contracts/common/DelegateProxy.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            contract DelegateProxy is ERCProxy, IsContract {
                                uint256 internal constant FWD_GAS_LIMIT = 10000;
                            
                                /**
                                * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!)
                                * @param _dst Destination address to perform the delegatecall
                                * @param _calldata Calldata for the delegatecall
                                */
                                function delegatedFwd(address _dst, bytes _calldata) internal {
                                    require(isContract(_dst));
                                    uint256 fwdGasLimit = FWD_GAS_LIMIT;
                            
                                    assembly {
                                        let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
                                        let size := returndatasize
                                        let ptr := mload(0x40)
                                        returndatacopy(ptr, 0, size)
                            
                                        // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
                                        // if the call returned error data, forward it
                                        switch result case 0 { revert(ptr, size) }
                                        default { return(ptr, size) }
                                    }
                                }
                            }
                            
                            // File: contracts/common/DepositableStorage.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            contract DepositableStorage {
                                using UnstructuredStorage for bytes32;
                            
                                // keccak256("aragonOS.depositableStorage.depositable")
                                bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea;
                            
                                function isDepositable() public view returns (bool) {
                                    return DEPOSITABLE_POSITION.getStorageBool();
                                }
                            
                                function setDepositable(bool _depositable) internal {
                                    DEPOSITABLE_POSITION.setStorageBool(_depositable);
                                }
                            }
                            
                            // File: contracts/common/DepositableDelegateProxy.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            contract DepositableDelegateProxy is DepositableStorage, DelegateProxy {
                                event ProxyDeposit(address sender, uint256 value);
                            
                                function () external payable {
                                    uint256 forwardGasThreshold = FWD_GAS_LIMIT;
                                    bytes32 isDepositablePosition = DEPOSITABLE_POSITION;
                            
                                    // Optimized assembly implementation to prevent EIP-1884 from breaking deposits, reference code in Solidity:
                                    // https://github.com/aragon/aragonOS/blob/v4.2.1/contracts/common/DepositableDelegateProxy.sol#L10-L20
                                    assembly {
                                        // Continue only if the gas left is lower than the threshold for forwarding to the implementation code,
                                        // otherwise continue outside of the assembly block.
                                        if lt(gas, forwardGasThreshold) {
                                            // Only accept the deposit and emit an event if all of the following are true:
                                            // the proxy accepts deposits (isDepositable), msg.data.length == 0, and msg.value > 0
                                            if and(and(sload(isDepositablePosition), iszero(calldatasize)), gt(callvalue, 0)) {
                                                // Equivalent Solidity code for emitting the event:
                                                // emit ProxyDeposit(msg.sender, msg.value);
                            
                                                let logData := mload(0x40) // free memory pointer
                                                mstore(logData, caller) // add 'msg.sender' to the log data (first event param)
                                                mstore(add(logData, 0x20), callvalue) // add 'msg.value' to the log data (second event param)
                            
                                                // Emit an event with one topic to identify the event: keccak256('ProxyDeposit(address,uint256)') = 0x15ee...dee1
                                                log1(logData, 0x40, 0x15eeaa57c7bd188c1388020bcadc2c436ec60d647d36ef5b9eb3c742217ddee1)
                            
                                                stop() // Stop. Exits execution context
                                            }
                            
                                            // If any of above checks failed, revert the execution (if ETH was sent, it is returned to the sender)
                                            revert(0, 0)
                                        }
                                    }
                            
                                    address target = implementation();
                                    delegatedFwd(target, msg.data);
                                }
                            }
                            
                            // File: contracts/apps/AppProxyBase.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            
                            
                            contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants {
                                /**
                                * @dev Initialize AppProxy
                                * @param _kernel Reference to organization kernel for the app
                                * @param _appId Identifier for app
                                * @param _initializePayload Payload for call to be made after setup to initialize
                                */
                                constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public {
                                    setKernel(_kernel);
                                    setAppId(_appId);
                            
                                    // Implicit check that kernel is actually a Kernel
                                    // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to
                                    // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on
                                    // it.
                                    address appCode = getAppBase(_appId);
                            
                                    // If initialize payload is provided, it will be executed
                                    if (_initializePayload.length > 0) {
                                        require(isContract(appCode));
                                        // Cannot make delegatecall as a delegateproxy.delegatedFwd as it
                                        // returns ending execution context and halts contract deployment
                                        require(appCode.delegatecall(_initializePayload));
                                    }
                                }
                            
                                function getAppBase(bytes32 _appId) internal view returns (address) {
                                    return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId);
                                }
                            }
                            
                            // File: contracts/apps/AppProxyUpgradeable.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            contract AppProxyUpgradeable is AppProxyBase {
                                /**
                                * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app)
                                * @param _kernel Reference to organization kernel for the app
                                * @param _appId Identifier for app
                                * @param _initializePayload Payload for call to be made after setup to initialize
                                */
                                constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
                                    AppProxyBase(_kernel, _appId, _initializePayload)
                                    public // solium-disable-line visibility-first
                                {
                                    // solium-disable-previous-line no-empty-blocks
                                }
                            
                                /**
                                 * @dev ERC897, the address the proxy would delegate calls to
                                 */
                                function implementation() public view returns (address) {
                                    return getAppBase(appId());
                                }
                            
                                /**
                                 * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
                                 */
                                function proxyType() public pure returns (uint256 proxyTypeId) {
                                    return UPGRADEABLE;
                                }
                            }
                            
                            // File: contracts/apps/AppProxyPinned.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            
                            contract AppProxyPinned is IsContract, AppProxyBase {
                                using UnstructuredStorage for bytes32;
                            
                                // keccak256("aragonOS.appStorage.pinnedCode")
                                bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e;
                            
                                /**
                                * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app)
                                * @param _kernel Reference to organization kernel for the app
                                * @param _appId Identifier for app
                                * @param _initializePayload Payload for call to be made after setup to initialize
                                */
                                constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
                                    AppProxyBase(_kernel, _appId, _initializePayload)
                                    public // solium-disable-line visibility-first
                                {
                                    setPinnedCode(getAppBase(_appId));
                                    require(isContract(pinnedCode()));
                                }
                            
                                /**
                                 * @dev ERC897, the address the proxy would delegate calls to
                                 */
                                function implementation() public view returns (address) {
                                    return pinnedCode();
                                }
                            
                                /**
                                 * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
                                 */
                                function proxyType() public pure returns (uint256 proxyTypeId) {
                                    return FORWARDING;
                                }
                            
                                function setPinnedCode(address _pinnedCode) internal {
                                    PINNED_CODE_POSITION.setStorageAddress(_pinnedCode);
                                }
                            
                                function pinnedCode() internal view returns (address) {
                                    return PINNED_CODE_POSITION.getStorageAddress();
                                }
                            }
                            
                            // File: contracts/factory/AppProxyFactory.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            contract AppProxyFactory {
                                event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId);
                            
                                /**
                                * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId`
                                * @param _kernel App's Kernel reference
                                * @param _appId Identifier for app
                                * @return AppProxyUpgradeable
                                */
                                function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) {
                                    return newAppProxy(_kernel, _appId, new bytes(0));
                                }
                            
                                /**
                                * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
                                * @param _kernel App's Kernel reference
                                * @param _appId Identifier for app
                                * @return AppProxyUpgradeable
                                */
                                function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) {
                                    AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload);
                                    emit NewAppProxy(address(proxy), true, _appId);
                                    return proxy;
                                }
                            
                                /**
                                * @notice Create a new pinned app instance on `_kernel` with identifier `_appId`
                                * @param _kernel App's Kernel reference
                                * @param _appId Identifier for app
                                * @return AppProxyPinned
                                */
                                function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) {
                                    return newAppProxyPinned(_kernel, _appId, new bytes(0));
                                }
                            
                                /**
                                * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
                                * @param _kernel App's Kernel reference
                                * @param _appId Identifier for app
                                * @param _initializePayload Proxy initialization payload
                                * @return AppProxyPinned
                                */
                                function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) {
                                    AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload);
                                    emit NewAppProxy(address(proxy), false, _appId);
                                    return proxy;
                                }
                            }
                            
                            // File: contracts/kernel/Kernel.sol
                            
                            pragma solidity 0.4.24;
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            // solium-disable-next-line max-len
                            contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar {
                                /* Hardcoded constants to save gas
                                bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE");
                                */
                                bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0;
                            
                                string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT";
                                string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE";
                                string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED";
                            
                                /**
                                * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately.
                                * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized
                                */
                                constructor(bool _shouldPetrify) public {
                                    if (_shouldPetrify) {
                                        petrify();
                                    }
                                }
                            
                                /**
                                * @dev Initialize can only be called once. It saves the block number in which it was initialized.
                                * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions
                                * @param _baseAcl Address of base ACL app
                                * @param _permissionsCreator Entity that will be given permission over createPermission
                                */
                                function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit {
                                    initialized();
                            
                                    // Set ACL base
                                    _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl);
                            
                                    // Create ACL instance and attach it as the default ACL app
                                    IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID));
                                    acl.initialize(_permissionsCreator);
                                    _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl);
                            
                                    recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID;
                                }
                            
                                /**
                                * @dev Create a new instance of an app linked to this kernel
                                * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`
                                * @param _appId Identifier for app
                                * @param _appBase Address of the app's base implementation
                                * @return AppProxy instance
                                */
                                function newAppInstance(bytes32 _appId, address _appBase)
                                    public
                                    auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                                    returns (ERCProxy appProxy)
                                {
                                    return newAppInstance(_appId, _appBase, new bytes(0), false);
                                }
                            
                                /**
                                * @dev Create a new instance of an app linked to this kernel and set its base
                                *      implementation if it was not already set
                                * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
                                * @param _appId Identifier for app
                                * @param _appBase Address of the app's base implementation
                                * @param _initializePayload Payload for call made by the proxy during its construction to initialize
                                * @param _setDefault Whether the app proxy app is the default one.
                                *        Useful when the Kernel needs to know of an instance of a particular app,
                                *        like Vault for escape hatch mechanism.
                                * @return AppProxy instance
                                */
                                function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
                                    public
                                    auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                                    returns (ERCProxy appProxy)
                                {
                                    _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
                                    appProxy = newAppProxy(this, _appId, _initializePayload);
                                    // By calling setApp directly and not the internal functions, we make sure the params are checked
                                    // and it will only succeed if sender has permissions to set something to the namespace.
                                    if (_setDefault) {
                                        setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
                                    }
                                }
                            
                                /**
                                * @dev Create a new pinned instance of an app linked to this kernel
                                * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`.
                                * @param _appId Identifier for app
                                * @param _appBase Address of the app's base implementation
                                * @return AppProxy instance
                                */
                                function newPinnedAppInstance(bytes32 _appId, address _appBase)
                                    public
                                    auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                                    returns (ERCProxy appProxy)
                                {
                                    return newPinnedAppInstance(_appId, _appBase, new bytes(0), false);
                                }
                            
                                /**
                                * @dev Create a new pinned instance of an app linked to this kernel and set
                                *      its base implementation if it was not already set
                                * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
                                * @param _appId Identifier for app
                                * @param _appBase Address of the app's base implementation
                                * @param _initializePayload Payload for call made by the proxy during its construction to initialize
                                * @param _setDefault Whether the app proxy app is the default one.
                                *        Useful when the Kernel needs to know of an instance of a particular app,
                                *        like Vault for escape hatch mechanism.
                                * @return AppProxy instance
                                */
                                function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
                                    public
                                    auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                                    returns (ERCProxy appProxy)
                                {
                                    _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
                                    appProxy = newAppProxyPinned(this, _appId, _initializePayload);
                                    // By calling setApp directly and not the internal functions, we make sure the params are checked
                                    // and it will only succeed if sender has permissions to set something to the namespace.
                                    if (_setDefault) {
                                        setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
                                    }
                                }
                            
                                /**
                                * @dev Set the resolving address of an app instance or base implementation
                                * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app`
                                * @param _namespace App namespace to use
                                * @param _appId Identifier for app
                                * @param _app Address of the app instance or base implementation
                                * @return ID of app
                                */
                                function setApp(bytes32 _namespace, bytes32 _appId, address _app)
                                    public
                                    auth(APP_MANAGER_ROLE, arr(_namespace, _appId))
                                {
                                    _setApp(_namespace, _appId, _app);
                                }
                            
                                /**
                                * @dev Set the default vault id for the escape hatch mechanism
                                * @param _recoveryVaultAppId Identifier of the recovery vault app
                                */
                                function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId)
                                    public
                                    auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId))
                                {
                                    recoveryVaultAppId = _recoveryVaultAppId;
                                }
                            
                                // External access to default app id and namespace constants to mimic default getters for constants
                                /* solium-disable function-order, mixedcase */
                                function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; }
                                function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; }
                                function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; }
                                function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; }
                                function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; }
                                /* solium-enable function-order, mixedcase */
                            
                                /**
                                * @dev Get the address of an app instance or base implementation
                                * @param _namespace App namespace to use
                                * @param _appId Identifier for app
                                * @return Address of the app
                                */
                                function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) {
                                    return apps[_namespace][_appId];
                                }
                            
                                /**
                                * @dev Get the address of the recovery Vault instance (to recover funds)
                                * @return Address of the Vault
                                */
                                function getRecoveryVault() public view returns (address) {
                                    return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId];
                                }
                            
                                /**
                                * @dev Get the installed ACL app
                                * @return ACL app
                                */
                                function acl() public view returns (IACL) {
                                    return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID));
                                }
                            
                                /**
                                * @dev Function called by apps to check ACL on kernel or to check permission status
                                * @param _who Sender of the original call
                                * @param _where Address of the app
                                * @param _what Identifier for a group of actions in app
                                * @param _how Extra data for ACL auth
                                * @return Boolean indicating whether the ACL allows the role or not.
                                *         Always returns false if the kernel hasn't been initialized yet.
                                */
                                function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) {
                                    IACL defaultAcl = acl();
                                    return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas)
                                        defaultAcl.hasPermission(_who, _where, _what, _how);
                                }
                            
                                function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal {
                                    require(isContract(_app), ERROR_APP_NOT_CONTRACT);
                                    apps[_namespace][_appId] = _app;
                                    emit SetApp(_namespace, _appId, _app);
                                }
                            
                                function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal {
                                    address app = getApp(_namespace, _appId);
                                    if (app != address(0)) {
                                        // The only way to set an app is if it passes the isContract check, so no need to check it again
                                        require(app == _app, ERROR_INVALID_APP_CHANGE);
                                    } else {
                                        _setApp(_namespace, _appId, _app);
                                    }
                                }
                            
                                modifier auth(bytes32 _role, uint256[] memory _params) {
                                    require(
                                        hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)),
                                        ERROR_AUTH_FAILED
                                    );
                                    _;
                                }
                            }

                            File 11 of 12: Lido
                            // SPDX-FileCopyrightText: 2020 Lido <[email protected]>
                            // SPDX-License-Identifier: GPL-3.0
                            pragma solidity 0.4.24;
                            /**
                              * @title Deposit contract interface
                              */
                            interface IDepositContract {
                                /**
                                  * @notice Top-ups deposit of a validator on the ETH 2.0 side
                                  * @param pubkey Validator signing key
                                  * @param withdrawal_credentials Credentials that allows to withdraw funds
                                  * @param signature Signature of the request
                                  * @param deposit_data_root The deposits Merkle tree node, used as a checksum
                                  */
                                function deposit(
                                    bytes /* 48 */ pubkey,
                                    bytes /* 32 */ withdrawal_credentials,
                                    bytes /* 96 */ signature,
                                    bytes32 deposit_data_root
                                )
                                    external payable;
                            }
                            // SPDX-FileCopyrightText: 2020 Lido <[email protected]>
                            // SPDX-License-Identifier: GPL-3.0
                            /* See contracts/COMPILERS.md */
                            pragma solidity 0.4.24;
                            import "@aragon/os/contracts/apps/AragonApp.sol";
                            import "@aragon/os/contracts/lib/math/SafeMath.sol";
                            import "@aragon/os/contracts/lib/math/SafeMath64.sol";
                            import "@aragon/os/contracts/common/IsContract.sol";
                            import "solidity-bytes-utils/contracts/BytesLib.sol";
                            import "./interfaces/ILido.sol";
                            import "./interfaces/INodeOperatorsRegistry.sol";
                            import "./interfaces/IDepositContract.sol";
                            import "./StETH.sol";
                            /**
                            * @title Liquid staking pool implementation
                            *
                            * Lido is an Ethereum 2.0 liquid staking protocol solving the problem of frozen staked Ethers
                            * until transfers become available in Ethereum 2.0.
                            * Whitepaper: https://lido.fi/static/Lido:Ethereum-Liquid-Staking.pdf
                            *
                            * NOTE: the code below assumes moderate amount of node operators, e.g. up to 50.
                            *
                            * Since balances of all token holders change when the amount of total pooled Ether
                            * changes, this token cannot fully implement ERC20 standard: it only emits `Transfer`
                            * events upon explicit transfer between holders. In contrast, when Lido oracle reports
                            * rewards, no Transfer events are generated: doing so would require emitting an event
                            * for each token holder and thus running an unbounded loop.
                            */
                            contract Lido is ILido, IsContract, StETH, AragonApp {
                                using SafeMath for uint256;
                                using SafeMath64 for uint64;
                                using UnstructuredStorage for bytes32;
                                /// ACL
                                bytes32 constant public PAUSE_ROLE = keccak256("PAUSE_ROLE");
                                bytes32 constant public MANAGE_FEE = keccak256("MANAGE_FEE");
                                bytes32 constant public MANAGE_WITHDRAWAL_KEY = keccak256("MANAGE_WITHDRAWAL_KEY");
                                bytes32 constant public SET_ORACLE = keccak256("SET_ORACLE");
                                bytes32 constant public BURN_ROLE = keccak256("BURN_ROLE");
                                bytes32 constant public SET_TREASURY = keccak256("SET_TREASURY");
                                bytes32 constant public SET_INSURANCE_FUND = keccak256("SET_INSURANCE_FUND");
                                bytes32 constant public DEPOSIT_ROLE = keccak256("DEPOSIT_ROLE");
                                uint256 constant public PUBKEY_LENGTH = 48;
                                uint256 constant public WITHDRAWAL_CREDENTIALS_LENGTH = 32;
                                uint256 constant public SIGNATURE_LENGTH = 96;
                                uint256 constant public DEPOSIT_SIZE = 32 ether;
                                uint256 internal constant DEPOSIT_AMOUNT_UNIT = 1000000000 wei;
                                /// @dev default value for maximum number of Ethereum 2.0 validators registered in a single depositBufferedEther call
                                uint256 internal constant DEFAULT_MAX_DEPOSITS_PER_CALL = 150;
                                bytes32 internal constant FEE_POSITION = keccak256("lido.Lido.fee");
                                bytes32 internal constant TREASURY_FEE_POSITION = keccak256("lido.Lido.treasuryFee");
                                bytes32 internal constant INSURANCE_FEE_POSITION = keccak256("lido.Lido.insuranceFee");
                                bytes32 internal constant NODE_OPERATORS_FEE_POSITION = keccak256("lido.Lido.nodeOperatorsFee");
                                bytes32 internal constant DEPOSIT_CONTRACT_POSITION = keccak256("lido.Lido.depositContract");
                                bytes32 internal constant ORACLE_POSITION = keccak256("lido.Lido.oracle");
                                bytes32 internal constant NODE_OPERATORS_REGISTRY_POSITION = keccak256("lido.Lido.nodeOperatorsRegistry");
                                bytes32 internal constant TREASURY_POSITION = keccak256("lido.Lido.treasury");
                                bytes32 internal constant INSURANCE_FUND_POSITION = keccak256("lido.Lido.insuranceFund");
                                /// @dev amount of Ether (on the current Ethereum side) buffered on this smart contract balance
                                bytes32 internal constant BUFFERED_ETHER_POSITION = keccak256("lido.Lido.bufferedEther");
                                /// @dev number of deposited validators (incrementing counter of deposit operations).
                                bytes32 internal constant DEPOSITED_VALIDATORS_POSITION = keccak256("lido.Lido.depositedValidators");
                                /// @dev total amount of Beacon-side Ether (sum of all the balances of Lido validators)
                                bytes32 internal constant BEACON_BALANCE_POSITION = keccak256("lido.Lido.beaconBalance");
                                /// @dev number of Lido's validators available in the Beacon state
                                bytes32 internal constant BEACON_VALIDATORS_POSITION = keccak256("lido.Lido.beaconValidators");
                                /// @dev Credentials which allows the DAO to withdraw Ether on the 2.0 side
                                bytes32 internal constant WITHDRAWAL_CREDENTIALS_POSITION = keccak256("lido.Lido.withdrawalCredentials");
                                /**
                                * @dev As AragonApp, Lido contract must be initialized with following variables:
                                * @param depositContract official ETH2 Deposit contract
                                * @param _oracle oracle contract
                                * @param _operators instance of Node Operators Registry
                                */
                                function initialize(
                                    IDepositContract depositContract,
                                    address _oracle,
                                    INodeOperatorsRegistry _operators,
                                    address _treasury,
                                    address _insuranceFund
                                )
                                    public onlyInit
                                {
                                    _setDepositContract(depositContract);
                                    _setOracle(_oracle);
                                    _setOperators(_operators);
                                    _setTreasury(_treasury);
                                    _setInsuranceFund(_insuranceFund);
                                    initialized();
                                }
                                /**
                                * @notice Send funds to the pool
                                * @dev Users are able to submit their funds by transacting to the fallback function.
                                * Unlike vanilla Eth2.0 Deposit contract, accepting only 32-Ether transactions, Lido
                                * accepts payments of any size. Submitted Ethers are stored in Buffer until someone calls
                                * depositBufferedEther() and pushes them to the ETH2 Deposit contract.
                                */
                                function() external payable {
                                    // protection against accidental submissions by calling non-existent function
                                    require(msg.data.length == 0, "NON_EMPTY_DATA");
                                    _submit(0);
                                }
                                /**
                                * @notice Send funds to the pool with optional _referral parameter
                                * @dev This function is alternative way to submit funds. Supports optional referral address.
                                * @return Amount of StETH shares generated
                                */
                                function submit(address _referral) external payable returns (uint256) {
                                    return _submit(_referral);
                                }
                                /**
                                * @notice Deposits buffered ethers to the official DepositContract.
                                * @dev This function is separated from submit() to reduce the cost of sending funds.
                                */
                                function depositBufferedEther() external auth(DEPOSIT_ROLE) {
                                    return _depositBufferedEther(DEFAULT_MAX_DEPOSITS_PER_CALL);
                                }
                                /**
                                  * @notice Deposits buffered ethers to the official DepositContract, making no more than `_maxDeposits` deposit calls.
                                  * @dev This function is separated from submit() to reduce the cost of sending funds.
                                  */
                                function depositBufferedEther(uint256 _maxDeposits) external auth(DEPOSIT_ROLE) {
                                    return _depositBufferedEther(_maxDeposits);
                                }
                                function burnShares(address _account, uint256 _sharesAmount)
                                    external
                                    authP(BURN_ROLE, arr(_account, _sharesAmount))
                                    returns (uint256 newTotalShares)
                                {
                                    return _burnShares(_account, _sharesAmount);
                                }
                                /**
                                  * @notice Stop pool routine operations
                                  */
                                function stop() external auth(PAUSE_ROLE) {
                                    _stop();
                                }
                                /**
                                  * @notice Resume pool routine operations
                                  */
                                function resume() external auth(PAUSE_ROLE) {
                                    _resume();
                                }
                                /**
                                  * @notice Set fee rate to `_feeBasisPoints` basis points. The fees are accrued when oracles report staking results
                                  * @param _feeBasisPoints Fee rate, in basis points
                                  */
                                function setFee(uint16 _feeBasisPoints) external auth(MANAGE_FEE) {
                                    _setBPValue(FEE_POSITION, _feeBasisPoints);
                                    emit FeeSet(_feeBasisPoints);
                                }
                                /**
                                  * @notice Set fee distribution: `_treasuryFeeBasisPoints` basis points go to the treasury, `_insuranceFeeBasisPoints` basis points go to the insurance fund, `_operatorsFeeBasisPoints` basis points go to node operators. The sum has to be 10 000.
                                  */
                                function setFeeDistribution(
                                    uint16 _treasuryFeeBasisPoints,
                                    uint16 _insuranceFeeBasisPoints,
                                    uint16 _operatorsFeeBasisPoints
                                )
                                    external auth(MANAGE_FEE)
                                {
                                    require(
                                        10000 == uint256(_treasuryFeeBasisPoints)
                                        .add(uint256(_insuranceFeeBasisPoints))
                                        .add(uint256(_operatorsFeeBasisPoints)),
                                        "FEES_DONT_ADD_UP"
                                    );
                                    _setBPValue(TREASURY_FEE_POSITION, _treasuryFeeBasisPoints);
                                    _setBPValue(INSURANCE_FEE_POSITION, _insuranceFeeBasisPoints);
                                    _setBPValue(NODE_OPERATORS_FEE_POSITION, _operatorsFeeBasisPoints);
                                    emit FeeDistributionSet(_treasuryFeeBasisPoints, _insuranceFeeBasisPoints, _operatorsFeeBasisPoints);
                                }
                                /**
                                  * @notice Set authorized oracle contract address to `_oracle`
                                  * @dev Contract specified here is allowed to make periodical updates of beacon states
                                  * by calling pushBeacon.
                                  * @param _oracle oracle contract
                                  */
                                function setOracle(address _oracle) external auth(SET_ORACLE) {
                                    _setOracle(_oracle);
                                }
                                /**
                                  * @notice Set treasury contract address to `_treasury`
                                  * @dev Contract specified here is used to accumulate the protocol treasury fee.
                                  * @param _treasury contract which accumulates treasury fee.
                                  */
                                function setTreasury(address _treasury) external auth(SET_TREASURY) {
                                    _setTreasury(_treasury);
                                }
                                /**
                                  * @notice Set insuranceFund contract address to `_insuranceFund`
                                  * @dev Contract specified here is used to accumulate the protocol insurance fee.
                                  * @param _insuranceFund contract which accumulates insurance fee.
                                  */
                                function setInsuranceFund(address _insuranceFund) external auth(SET_INSURANCE_FUND) {
                                    _setInsuranceFund(_insuranceFund);
                                }
                                /**
                                  * @notice Set credentials to withdraw ETH on ETH 2.0 side after the phase 2 is launched to `_withdrawalCredentials`
                                  * @dev Note that setWithdrawalCredentials discards all unused signing keys as the signatures are invalidated.
                                  * @param _withdrawalCredentials hash of withdrawal multisignature key as accepted by
                                  *        the deposit_contract.deposit function
                                  */
                                function setWithdrawalCredentials(bytes32 _withdrawalCredentials) external auth(MANAGE_WITHDRAWAL_KEY) {
                                    WITHDRAWAL_CREDENTIALS_POSITION.setStorageBytes32(_withdrawalCredentials);
                                    getOperators().trimUnusedKeys();
                                    emit WithdrawalCredentialsSet(_withdrawalCredentials);
                                }
                                /**
                                  * @notice Issues withdrawal request. Not implemented.
                                  * @param _amount Amount of StETH to withdraw
                                  * @param _pubkeyHash Receiving address
                                  */
                                function withdraw(uint256 _amount, bytes32 _pubkeyHash) external whenNotStopped { /* solhint-disable-line no-unused-vars */
                                    //will be upgraded to an actual implementation when withdrawals are enabled (Phase 1.5 or 2 of Eth2 launch, likely late 2021 or 2022).
                                    //at the moment withdrawals are not possible in the beacon chain and there's no workaround
                                    revert("NOT_IMPLEMENTED_YET");
                                }
                                /**
                                * @notice Updates the number of Lido-controlled keys in the beacon validators set and their total balance.
                                * @dev periodically called by the Oracle contract
                                * @param _beaconValidators number of Lido's keys in the beacon state
                                * @param _beaconBalance simmarized balance of Lido-controlled keys in wei
                                */
                                function pushBeacon(uint256 _beaconValidators, uint256 _beaconBalance) external whenNotStopped {
                                    require(msg.sender == getOracle(), "APP_AUTH_FAILED");
                                    uint256 depositedValidators = DEPOSITED_VALIDATORS_POSITION.getStorageUint256();
                                    require(_beaconValidators <= depositedValidators, "REPORTED_MORE_DEPOSITED");
                                    uint256 beaconValidators = BEACON_VALIDATORS_POSITION.getStorageUint256();
                                    // Since the calculation of funds in the ingress queue is based on the number of validators
                                    // that are in a transient state (deposited but not seen on beacon yet), we can't decrease the previously
                                    // reported number (we'll be unable to figure out who is in the queue and count them).
                                    // See LIP-1 for details https://github.com/lidofinance/lido-improvement-proposals/blob/develop/LIPS/lip-1.md
                                    require(_beaconValidators >= beaconValidators, "REPORTED_LESS_VALIDATORS");
                                    uint256 appearedValidators = _beaconValidators.sub(beaconValidators);
                                    // RewardBase is the amount of money that is not included in the reward calculation
                                    // Just appeared validators * 32 added to the previously reported beacon balance
                                    uint256 rewardBase = (appearedValidators.mul(DEPOSIT_SIZE)).add(BEACON_BALANCE_POSITION.getStorageUint256());
                                    // Save the current beacon balance and validators to
                                    // calcuate rewards on the next push
                                    BEACON_BALANCE_POSITION.setStorageUint256(_beaconBalance);
                                    BEACON_VALIDATORS_POSITION.setStorageUint256(_beaconValidators);
                                    if (_beaconBalance > rewardBase) {
                                        uint256 rewards = _beaconBalance.sub(rewardBase);
                                        distributeRewards(rewards);
                                    }
                                }
                                /**
                                  * @notice Send funds to recovery Vault. Overrides default AragonApp behaviour.
                                  * @param _token Token to be sent to recovery vault.
                                  */
                                function transferToVault(address _token) external {
                                    require(allowRecoverability(_token), "RECOVER_DISALLOWED");
                                    address vault = getRecoveryVault();
                                    require(isContract(vault), "RECOVER_VAULT_NOT_CONTRACT");
                                    uint256 balance;
                                    if (_token == ETH) {
                                        balance = _getUnaccountedEther();
                                        // Transfer replaced by call to prevent transfer gas amount issue    
                                        require(vault.call.value(balance)(), "RECOVER_TRANSFER_FAILED");
                                    } else {
                                        ERC20 token = ERC20(_token);
                                        balance = token.staticBalanceOf(this);
                                        // safeTransfer comes from overriden default implementation
                                        require(token.safeTransfer(vault, balance), "RECOVER_TOKEN_TRANSFER_FAILED");
                                    }
                                    emit RecoverToVault(vault, _token, balance);
                                }
                                /**
                                  * @notice Returns staking rewards fee rate
                                  */
                                function getFee() external view returns (uint16 feeBasisPoints) {
                                    return _getFee();
                                }
                                /**
                                  * @notice Returns fee distribution proportion
                                  */
                                function getFeeDistribution()
                                    external
                                    view
                                    returns (
                                        uint16 treasuryFeeBasisPoints,
                                        uint16 insuranceFeeBasisPoints,
                                        uint16 operatorsFeeBasisPoints
                                    )
                                {
                                    return _getFeeDistribution();
                                }
                                /**
                                  * @notice Returns current credentials to withdraw ETH on ETH 2.0 side after the phase 2 is launched
                                  */
                                function getWithdrawalCredentials() public view returns (bytes32) {
                                    return WITHDRAWAL_CREDENTIALS_POSITION.getStorageBytes32();
                                }
                                /**
                                * @notice Get the amount of Ether temporary buffered on this contract balance
                                * @dev Buffered balance is kept on the contract from the moment the funds are received from user
                                * until the moment they are actually sent to the official Deposit contract.
                                * @return uint256 of buffered funds in wei
                                */
                                function getBufferedEther() external view returns (uint256) {
                                    return _getBufferedEther();
                                }
                                /**
                                  * @notice Gets deposit contract handle
                                  */
                                function getDepositContract() public view returns (IDepositContract) {
                                    return IDepositContract(DEPOSIT_CONTRACT_POSITION.getStorageAddress());
                                }
                                /**
                                * @notice Gets authorized oracle address
                                * @return address of oracle contract
                                */
                                function getOracle() public view returns (address) {
                                    return ORACLE_POSITION.getStorageAddress();
                                }
                                /**
                                  * @notice Gets node operators registry interface handle
                                  */
                                function getOperators() public view returns (INodeOperatorsRegistry) {
                                    return INodeOperatorsRegistry(NODE_OPERATORS_REGISTRY_POSITION.getStorageAddress());
                                }
                                /**
                                  * @notice Returns the treasury address
                                  */
                                function getTreasury() public view returns (address) {
                                    return TREASURY_POSITION.getStorageAddress();
                                }
                                /**
                                  * @notice Returns the insurance fund address
                                  */
                                function getInsuranceFund() public view returns (address) {
                                    return INSURANCE_FUND_POSITION.getStorageAddress();
                                }
                                /**
                                * @notice Returns the key values related to Beacon-side
                                * @return depositedValidators - number of deposited validators
                                * @return beaconValidators - number of Lido's validators visible in the Beacon state, reported by oracles
                                * @return beaconBalance - total amount of Beacon-side Ether (sum of all the balances of Lido validators)
                                */
                                function getBeaconStat() public view returns (uint256 depositedValidators, uint256 beaconValidators, uint256 beaconBalance) {
                                    depositedValidators = DEPOSITED_VALIDATORS_POSITION.getStorageUint256();
                                    beaconValidators = BEACON_VALIDATORS_POSITION.getStorageUint256();
                                    beaconBalance = BEACON_BALANCE_POSITION.getStorageUint256();
                                }
                                /**
                                * @dev Sets the address of Deposit contract
                                * @param _contract the address of Deposit contract
                                */
                                function _setDepositContract(IDepositContract _contract) internal {
                                    require(isContract(address(_contract)), "NOT_A_CONTRACT");
                                    DEPOSIT_CONTRACT_POSITION.setStorageAddress(address(_contract));
                                }
                                /**
                                * @dev Internal function to set authorized oracle address
                                * @param _oracle oracle contract
                                */
                                function _setOracle(address _oracle) internal {
                                    require(isContract(_oracle), "NOT_A_CONTRACT");
                                    ORACLE_POSITION.setStorageAddress(_oracle);
                                }
                                /**
                                * @dev Internal function to set node operator registry address
                                * @param _r registry of node operators
                                */
                                function _setOperators(INodeOperatorsRegistry _r) internal {
                                    require(isContract(_r), "NOT_A_CONTRACT");
                                    NODE_OPERATORS_REGISTRY_POSITION.setStorageAddress(_r);
                                }
                                function _setTreasury(address _treasury) internal {
                                    require(_treasury != address(0), "SET_TREASURY_ZERO_ADDRESS");
                                    TREASURY_POSITION.setStorageAddress(_treasury);
                                }
                                function _setInsuranceFund(address _insuranceFund) internal {
                                    require(_insuranceFund != address(0), "SET_INSURANCE_FUND_ZERO_ADDRESS");
                                    INSURANCE_FUND_POSITION.setStorageAddress(_insuranceFund);
                                }
                                /**
                                * @dev Process user deposit, mints liquid tokens and increase the pool buffer
                                * @param _referral address of referral.
                                * @return amount of StETH shares generated
                                */
                                function _submit(address _referral) internal whenNotStopped returns (uint256) {
                                    address sender = msg.sender;
                                    uint256 deposit = msg.value;
                                    require(deposit != 0, "ZERO_DEPOSIT");
                                    uint256 sharesAmount = getSharesByPooledEth(deposit);
                                    if (sharesAmount == 0) {
                                        // totalControlledEther is 0: either the first-ever deposit or complete slashing
                                        // assume that shares correspond to Ether 1-to-1
                                        sharesAmount = deposit;
                                    }
                                    _mintShares(sender, sharesAmount);
                                    _submitted(sender, deposit, _referral);
                                    _emitTransferAfterMintingShares(sender, sharesAmount);
                                    return sharesAmount;
                                }
                                /**
                                 * @dev Emits an {Transfer} event where from is 0 address. Indicates mint events.
                                 */
                                function _emitTransferAfterMintingShares(address _to, uint256 _sharesAmount) internal {
                                    emit Transfer(address(0), _to, getPooledEthByShares(_sharesAmount));
                                }
                                /**
                                * @dev Deposits buffered eth to the DepositContract and assigns chunked deposits to node operators
                                */
                                function _depositBufferedEther(uint256 _maxDeposits) internal whenNotStopped {
                                    uint256 buffered = _getBufferedEther();
                                    if (buffered >= DEPOSIT_SIZE) {
                                        uint256 unaccounted = _getUnaccountedEther();
                                        uint256 numDeposits = buffered.div(DEPOSIT_SIZE);
                                        _markAsUnbuffered(_ETH2Deposit(numDeposits < _maxDeposits ? numDeposits : _maxDeposits));
                                        assert(_getUnaccountedEther() == unaccounted);
                                    }
                                }
                                /**
                                * @dev Performs deposits to the ETH 2.0 side
                                * @param _numDeposits Number of deposits to perform
                                * @return actually deposited Ether amount
                                */
                                function _ETH2Deposit(uint256 _numDeposits) internal returns (uint256) {
                                    (bytes memory pubkeys, bytes memory signatures) = getOperators().assignNextSigningKeys(_numDeposits);
                                    if (pubkeys.length == 0) {
                                        return 0;
                                    }
                                    require(pubkeys.length.mod(PUBKEY_LENGTH) == 0, "REGISTRY_INCONSISTENT_PUBKEYS_LEN");
                                    require(signatures.length.mod(SIGNATURE_LENGTH) == 0, "REGISTRY_INCONSISTENT_SIG_LEN");
                                    uint256 numKeys = pubkeys.length.div(PUBKEY_LENGTH);
                                    require(numKeys == signatures.length.div(SIGNATURE_LENGTH), "REGISTRY_INCONSISTENT_SIG_COUNT");
                                    for (uint256 i = 0; i < numKeys; ++i) {
                                        bytes memory pubkey = BytesLib.slice(pubkeys, i * PUBKEY_LENGTH, PUBKEY_LENGTH);
                                        bytes memory signature = BytesLib.slice(signatures, i * SIGNATURE_LENGTH, SIGNATURE_LENGTH);
                                        _stake(pubkey, signature);
                                    }
                                    DEPOSITED_VALIDATORS_POSITION.setStorageUint256(
                                        DEPOSITED_VALIDATORS_POSITION.getStorageUint256().add(numKeys)
                                    );
                                    return numKeys.mul(DEPOSIT_SIZE);
                                }
                                /**
                                * @dev Invokes a deposit call to the official Deposit contract
                                * @param _pubkey Validator to stake for
                                * @param _signature Signature of the deposit call
                                */
                                function _stake(bytes memory _pubkey, bytes memory _signature) internal {
                                    bytes32 withdrawalCredentials = getWithdrawalCredentials();
                                    require(withdrawalCredentials != 0, "EMPTY_WITHDRAWAL_CREDENTIALS");
                                    uint256 value = DEPOSIT_SIZE;
                                    // The following computations and Merkle tree-ization will make official Deposit contract happy
                                    uint256 depositAmount = value.div(DEPOSIT_AMOUNT_UNIT);
                                    assert(depositAmount.mul(DEPOSIT_AMOUNT_UNIT) == value);    // properly rounded
                                    // Compute deposit data root (`DepositData` hash tree root) according to deposit_contract.sol
                                    bytes32 pubkeyRoot = sha256(_pad64(_pubkey));
                                    bytes32 signatureRoot = sha256(
                                        abi.encodePacked(
                                            sha256(BytesLib.slice(_signature, 0, 64)),
                                            sha256(_pad64(BytesLib.slice(_signature, 64, SIGNATURE_LENGTH.sub(64))))
                                        )
                                    );
                                    bytes32 depositDataRoot = sha256(
                                        abi.encodePacked(
                                            sha256(abi.encodePacked(pubkeyRoot, withdrawalCredentials)),
                                            sha256(abi.encodePacked(_toLittleEndian64(depositAmount), signatureRoot))
                                        )
                                    );
                                    uint256 targetBalance = address(this).balance.sub(value);
                                    getDepositContract().deposit.value(value)(
                                        _pubkey, abi.encodePacked(withdrawalCredentials), _signature, depositDataRoot);
                                    require(address(this).balance == targetBalance, "EXPECTING_DEPOSIT_TO_HAPPEN");
                                }
                                /**
                                * @dev Distributes rewards by minting and distributing corresponding amount of liquid tokens.
                                * @param _totalRewards Total rewards accrued on the Ethereum 2.0 side in wei
                                */
                                function distributeRewards(uint256 _totalRewards) internal {
                                    // We need to take a defined percentage of the reported reward as a fee, and we do
                                    // this by minting new token shares and assigning them to the fee recipients (see
                                    // StETH docs for the explanation of the shares mechanics). The staking rewards fee
                                    // is defined in basis points (1 basis point is equal to 0.01%, 10000 is 100%).
                                    //
                                    // Since we've increased totalPooledEther by _totalRewards (which is already
                                    // performed by the time this function is called), the combined cost of all holders'
                                    // shares has became _totalRewards StETH tokens more, effectively splitting the reward
                                    // between each token holder proportionally to their token share.
                                    //
                                    // Now we want to mint new shares to the fee recipient, so that the total cost of the
                                    // newly-minted shares exactly corresponds to the fee taken:
                                    //
                                    // shares2mint * newShareCost = (_totalRewards * feeBasis) / 10000
                                    // newShareCost = newTotalPooledEther / (prevTotalShares + shares2mint)
                                    //
                                    // which follows to:
                                    //
                                    //                        _totalRewards * feeBasis * prevTotalShares
                                    // shares2mint = --------------------------------------------------------------
                                    //                 (newTotalPooledEther * 10000) - (feeBasis * _totalRewards)
                                    //
                                    // The effect is that the given percentage of the reward goes to the fee recipient, and
                                    // the rest of the reward is distributed between token holders proportionally to their
                                    // token shares.
                                    uint256 feeBasis = _getFee();
                                    uint256 shares2mint = (
                                        _totalRewards.mul(feeBasis).mul(_getTotalShares())
                                        .div(
                                            _getTotalPooledEther().mul(10000)
                                            .sub(feeBasis.mul(_totalRewards))
                                        )
                                    );
                                    // Mint the calculated amount of shares to this contract address. This will reduce the
                                    // balances of the holders, as if the fee was taken in parts from each of them.
                                    _mintShares(address(this), shares2mint);
                                    (,uint16 insuranceFeeBasisPoints, uint16 operatorsFeeBasisPoints) = _getFeeDistribution();
                                    uint256 toInsuranceFund = shares2mint.mul(insuranceFeeBasisPoints).div(10000);
                                    address insuranceFund = getInsuranceFund();
                                    _transferShares(address(this), insuranceFund, toInsuranceFund);
                                    _emitTransferAfterMintingShares(insuranceFund, toInsuranceFund);
                                    uint256 distributedToOperatorsShares = _distributeNodeOperatorsReward(
                                        shares2mint.mul(operatorsFeeBasisPoints).div(10000)
                                    );
                                    // Transfer the rest of the fee to treasury
                                    uint256 toTreasury = shares2mint.sub(toInsuranceFund).sub(distributedToOperatorsShares);
                                    address treasury = getTreasury();
                                    _transferShares(address(this), treasury, toTreasury);
                                    _emitTransferAfterMintingShares(treasury, toTreasury);
                                }
                                function _distributeNodeOperatorsReward(uint256 _sharesToDistribute) internal returns (uint256 distributed) {
                                    (address[] memory recipients, uint256[] memory shares) = getOperators().getRewardsDistribution(_sharesToDistribute);
                                    assert(recipients.length == shares.length);
                                    distributed = 0;
                                    for (uint256 idx = 0; idx < recipients.length; ++idx) {
                                        _transferShares(
                                            address(this),
                                            recipients[idx],
                                            shares[idx]
                                        );
                                        _emitTransferAfterMintingShares(recipients[idx], shares[idx]);
                                        distributed = distributed.add(shares[idx]);
                                    }
                                }
                                /**
                                * @dev Records a deposit made by a user with optional referral
                                * @param _sender sender's address
                                * @param _value Deposit value in wei
                                * @param _referral address of the referral
                                */
                                function _submitted(address _sender, uint256 _value, address _referral) internal {
                                    BUFFERED_ETHER_POSITION.setStorageUint256(_getBufferedEther().add(_value));
                                    emit Submitted(_sender, _value, _referral);
                                }
                                /**
                                  * @dev Records a deposit to the deposit_contract.deposit function.
                                  * @param _amount Total amount deposited to the ETH 2.0 side
                                  */
                                function _markAsUnbuffered(uint256 _amount) internal {
                                    BUFFERED_ETHER_POSITION.setStorageUint256(
                                        BUFFERED_ETHER_POSITION.getStorageUint256().sub(_amount));
                                    emit Unbuffered(_amount);
                                }
                                /**
                                  * @dev Write a value nominated in basis points
                                  */
                                function _setBPValue(bytes32 _slot, uint16 _value) internal {
                                    require(_value <= 10000, "VALUE_OVER_100_PERCENT");
                                    _slot.setStorageUint256(uint256(_value));
                                }
                                /**
                                  * @dev Returns staking rewards fee rate
                                  */
                                function _getFee() internal view returns (uint16) {
                                    return _readBPValue(FEE_POSITION);
                                }
                                /**
                                  * @dev Returns fee distribution proportion
                                  */
                                function _getFeeDistribution() internal view
                                    returns (uint16 treasuryFeeBasisPoints, uint16 insuranceFeeBasisPoints, uint16 operatorsFeeBasisPoints)
                                {
                                    treasuryFeeBasisPoints = _readBPValue(TREASURY_FEE_POSITION);
                                    insuranceFeeBasisPoints = _readBPValue(INSURANCE_FEE_POSITION);
                                    operatorsFeeBasisPoints = _readBPValue(NODE_OPERATORS_FEE_POSITION);
                                }
                                /**
                                  * @dev Read a value nominated in basis points
                                  */
                                function _readBPValue(bytes32 _slot) internal view returns (uint16) {
                                    uint256 v = _slot.getStorageUint256();
                                    assert(v <= 10000);
                                    return uint16(v);
                                }
                                /**
                                  * @dev Gets the amount of Ether temporary buffered on this contract balance
                                  */
                                function _getBufferedEther() internal view returns (uint256) {
                                    uint256 buffered = BUFFERED_ETHER_POSITION.getStorageUint256();
                                    assert(address(this).balance >= buffered);
                                    return buffered;
                                }
                                /**
                                  * @dev Gets unaccounted (excess) Ether on this contract balance
                                  */
                                function _getUnaccountedEther() internal view returns (uint256) {
                                    return address(this).balance.sub(_getBufferedEther());
                                }
                                /**
                                * @dev Calculates and returns the total base balance (multiple of 32) of validators in transient state,
                                *      i.e. submitted to the official Deposit contract but not yet visible in the beacon state.
                                * @return transient balance in wei (1e-18 Ether)
                                */
                                function _getTransientBalance() internal view returns (uint256) {
                                    uint256 depositedValidators = DEPOSITED_VALIDATORS_POSITION.getStorageUint256();
                                    uint256 beaconValidators = BEACON_VALIDATORS_POSITION.getStorageUint256();
                                    // beaconValidators can never be less than deposited ones.
                                    assert(depositedValidators >= beaconValidators);
                                    uint256 transientValidators = depositedValidators.sub(beaconValidators);
                                    return transientValidators.mul(DEPOSIT_SIZE);
                                }
                                /**
                                * @dev Gets the total amount of Ether controlled by the system
                                * @return total balance in wei
                                */
                                function _getTotalPooledEther() internal view returns (uint256) {
                                    uint256 bufferedBalance = _getBufferedEther();
                                    uint256 beaconBalance = BEACON_BALANCE_POSITION.getStorageUint256();
                                    uint256 transientBalance = _getTransientBalance();
                                    return bufferedBalance.add(beaconBalance).add(transientBalance);
                                }
                                /**
                                  * @dev Padding memory array with zeroes up to 64 bytes on the right
                                  * @param _b Memory array of size 32 .. 64
                                  */
                                function _pad64(bytes memory _b) internal pure returns (bytes memory) {
                                    assert(_b.length >= 32 && _b.length <= 64);
                                    if (64 == _b.length)
                                        return _b;
                                    bytes memory zero32 = new bytes(32);
                                    assembly { mstore(add(zero32, 0x20), 0) }
                                    if (32 == _b.length)
                                        return BytesLib.concat(_b, zero32);
                                    else
                                        return BytesLib.concat(_b, BytesLib.slice(zero32, 0, uint256(64).sub(_b.length)));
                                }
                                /**
                                  * @dev Converting value to little endian bytes and padding up to 32 bytes on the right
                                  * @param _value Number less than `2**64` for compatibility reasons
                                  */
                                function _toLittleEndian64(uint256 _value) internal pure returns (uint256 result) {
                                    result = 0;
                                    uint256 temp_value = _value;
                                    for (uint256 i = 0; i < 8; ++i) {
                                        result = (result << 8) | (temp_value & 0xFF);
                                        temp_value >>= 8;
                                    }
                                    assert(0 == temp_value);    // fully converted
                                    result <<= (24 * 8);
                                }
                                function to64(uint256 v) internal pure returns (uint64) {
                                    assert(v <= uint256(uint64(-1)));
                                    return uint64(v);
                                }
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            import "./AppStorage.sol";
                            import "../acl/ACLSyntaxSugar.sol";
                            import "../common/Autopetrified.sol";
                            import "../common/ConversionHelpers.sol";
                            import "../common/ReentrancyGuard.sol";
                            import "../common/VaultRecoverable.sol";
                            import "../evmscript/EVMScriptRunner.sol";
                            // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so
                            // that they can never be initialized.
                            // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy.
                            // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but
                            // are included so that they are automatically usable by subclassing contracts
                            contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar {
                                string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED";
                                modifier auth(bytes32 _role) {
                                    require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED);
                                    _;
                                }
                                modifier authP(bytes32 _role, uint256[] _params) {
                                    require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED);
                                    _;
                                }
                                /**
                                * @dev Check whether an action can be performed by a sender for a particular role on this app
                                * @param _sender Sender of the call
                                * @param _role Role on this app
                                * @param _params Permission params for the role
                                * @return Boolean indicating whether the sender has the permissions to perform the action.
                                *         Always returns false if the app hasn't been initialized yet.
                                */
                                function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) {
                                    if (!hasInitialized()) {
                                        return false;
                                    }
                                    IKernel linkedKernel = kernel();
                                    if (address(linkedKernel) == address(0)) {
                                        return false;
                                    }
                                    return linkedKernel.hasPermission(
                                        _sender,
                                        address(this),
                                        _role,
                                        ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)
                                    );
                                }
                                /**
                                * @dev Get the recovery vault for the app
                                * @return Recovery vault address for the app
                                */
                                function getRecoveryVault() public view returns (address) {
                                    // Funds recovery via a vault is only available when used with a kernel
                                    return kernel().getRecoveryVault(); // if kernel is not set, it will revert
                                }
                            }
                            // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
                            // Adapted to use pragma ^0.4.24 and satisfy our linter rules
                            pragma solidity ^0.4.24;
                            /**
                             * @title SafeMath
                             * @dev Math operations with safety checks that revert on error
                             */
                            library SafeMath {
                                string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
                                string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
                                string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
                                string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
                                /**
                                * @dev Multiplies two numbers, reverts on 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-solidity/pull/522
                                    if (_a == 0) {
                                        return 0;
                                    }
                                    uint256 c = _a * _b;
                                    require(c / _a == _b, ERROR_MUL_OVERFLOW);
                                    return c;
                                }
                                /**
                                * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
                                */
                                function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
                                    require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
                                    uint256 c = _a / _b;
                                    // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
                                    return c;
                                }
                                /**
                                * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
                                */
                                function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
                                    require(_b <= _a, ERROR_SUB_UNDERFLOW);
                                    uint256 c = _a - _b;
                                    return c;
                                }
                                /**
                                * @dev Adds two numbers, reverts on overflow.
                                */
                                function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
                                    uint256 c = _a + _b;
                                    require(c >= _a, ERROR_ADD_OVERFLOW);
                                    return c;
                                }
                                /**
                                * @dev Divides two numbers and returns the remainder (unsigned integer modulo),
                                * reverts when dividing by zero.
                                */
                                function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                    require(b != 0, ERROR_DIV_ZERO);
                                    return a % b;
                                }
                            }
                            // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
                            // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules
                            // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417
                            pragma solidity ^0.4.24;
                            /**
                             * @title SafeMath64
                             * @dev Math operations for uint64 with safety checks that revert on error
                             */
                            library SafeMath64 {
                                string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
                                string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
                                string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
                                string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
                                /**
                                * @dev Multiplies two numbers, reverts on overflow.
                                */
                                function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
                                    uint256 c = uint256(_a) * uint256(_b);
                                    require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
                                    return uint64(c);
                                }
                                /**
                                * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
                                */
                                function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
                                    require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
                                    uint64 c = _a / _b;
                                    // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
                                    return c;
                                }
                                /**
                                * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
                                */
                                function sub(uint64 _a, uint64 _b) internal pure returns (uint64) {
                                    require(_b <= _a, ERROR_SUB_UNDERFLOW);
                                    uint64 c = _a - _b;
                                    return c;
                                }
                                /**
                                * @dev Adds two numbers, reverts on overflow.
                                */
                                function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
                                    uint64 c = _a + _b;
                                    require(c >= _a, ERROR_ADD_OVERFLOW);
                                    return c;
                                }
                                /**
                                * @dev Divides two numbers and returns the remainder (unsigned integer modulo),
                                * reverts when dividing by zero.
                                */
                                function mod(uint64 a, uint64 b) internal pure returns (uint64) {
                                    require(b != 0, ERROR_DIV_ZERO);
                                    return a % b;
                                }
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            contract IsContract {
                                /*
                                * NOTE: this should NEVER be used for authentication
                                * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
                                *
                                * This is only intended to be used as a sanity check that an address is actually a contract,
                                * RATHER THAN an address not being a contract.
                                */
                                function isContract(address _target) internal view returns (bool) {
                                    if (_target == address(0)) {
                                        return false;
                                    }
                                    uint256 size;
                                    assembly { size := extcodesize(_target) }
                                    return size > 0;
                                }
                            }
                            /*
                             * @title Solidity Bytes Arrays Utils
                             * @author Gonçalo Sá <[email protected]>
                             *
                             * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
                             *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
                             */
                            pragma solidity ^0.4.19;
                            library BytesLib {
                                function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes) {
                                    bytes memory tempBytes;
                                    assembly {
                                        // Get a location of some free memory and store it in tempBytes as
                                        // Solidity does for memory variables.
                                        tempBytes := mload(0x40)
                                        // Store the length of the first bytes array at the beginning of
                                        // the memory for tempBytes.
                                        let length := mload(_preBytes)
                                        mstore(tempBytes, length)
                                        // Maintain a memory counter for the current write location in the
                                        // temp bytes array by adding the 32 bytes for the array length to
                                        // the starting location.
                                        let mc := add(tempBytes, 0x20)
                                        // Stop copying when the memory counter reaches the length of the
                                        // first bytes array.
                                        let end := add(mc, length)
                                        for {
                                            // Initialize a copy counter to the start of the _preBytes data,
                                            // 32 bytes into its memory.
                                            let cc := add(_preBytes, 0x20)
                                        } lt(mc, end) {
                                            // Increase both counters by 32 bytes each iteration.
                                            mc := add(mc, 0x20)
                                            cc := add(cc, 0x20)
                                        } {
                                            // Write the _preBytes data into the tempBytes memory 32 bytes
                                            // at a time.
                                            mstore(mc, mload(cc))
                                        }
                                        // Add the length of _postBytes to the current length of tempBytes
                                        // and store it as the new length in the first 32 bytes of the
                                        // tempBytes memory.
                                        length := mload(_postBytes)
                                        mstore(tempBytes, add(length, mload(tempBytes)))
                                        // Move the memory counter back from a multiple of 0x20 to the
                                        // actual end of the _preBytes data.
                                        mc := end
                                        // Stop copying when the memory counter reaches the new combined
                                        // length of the arrays.
                                        end := add(mc, length)
                                        for {
                                            let cc := add(_postBytes, 0x20)
                                        } lt(mc, end) {
                                            mc := add(mc, 0x20)
                                            cc := add(cc, 0x20)
                                        } {
                                            mstore(mc, mload(cc))
                                        }
                                        // Update the free-memory pointer by padding our last write location
                                        // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
                                        // next 32 byte block, then round down to the nearest multiple of
                                        // 32. If the sum of the length of the two arrays is zero then add 
                                        // one before rounding down to leave a blank 32 bytes (the length block with 0).
                                        mstore(0x40, and(
                                          add(add(end, iszero(add(length, mload(_preBytes)))), 31),
                                          not(31) // Round down to the nearest 32 bytes.
                                        ))
                                    }
                                    return tempBytes;
                                }
                                function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
                                    assembly {
                                        // Read the first 32 bytes of _preBytes storage, which is the length
                                        // of the array. (We don't need to use the offset into the slot
                                        // because arrays use the entire slot.)
                                        let fslot := sload(_preBytes_slot)
                                        // Arrays of 31 bytes or less have an even value in their slot,
                                        // while longer arrays have an odd value. The actual length is
                                        // the slot divided by two for odd values, and the lowest order
                                        // byte divided by two for even values.
                                        // If the slot is even, bitwise and the slot with 255 and divide by
                                        // two to get the length. If the slot is odd, bitwise and the slot
                                        // with -1 and divide by two.
                                        let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                                        let mlength := mload(_postBytes)
                                        let newlength := add(slength, mlength)
                                        // slength can contain both the length and contents of the array
                                        // if length < 32 bytes so let's prepare for that
                                        // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                                        switch add(lt(slength, 32), lt(newlength, 32))
                                        case 2 {
                                            // Since the new array still fits in the slot, we just need to
                                            // update the contents of the slot.
                                            // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
                                            sstore(
                                                _preBytes_slot,
                                                // all the modifications to the slot are inside this
                                                // next block
                                                add(
                                                    // we can just add to the slot contents because the
                                                    // bytes we want to change are the LSBs
                                                    fslot,
                                                    add(
                                                        mul(
                                                            div(
                                                                // load the bytes from memory
                                                                mload(add(_postBytes, 0x20)),
                                                                // zero all bytes to the right
                                                                exp(0x100, sub(32, mlength))
                                                            ),
                                                            // and now shift left the number of bytes to
                                                            // leave space for the length in the slot
                                                            exp(0x100, sub(32, newlength))
                                                        ),
                                                        // increase length by the double of the memory
                                                        // bytes length
                                                        mul(mlength, 2)
                                                    )
                                                )
                                            )
                                        }
                                        case 1 {
                                            // The stored value fits in the slot, but the combined value
                                            // will exceed it.
                                            // get the keccak hash to get the contents of the array
                                            mstore(0x0, _preBytes_slot)
                                            let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                                            // save new length
                                            sstore(_preBytes_slot, add(mul(newlength, 2), 1))
                                            // The contents of the _postBytes array start 32 bytes into
                                            // the structure. Our first read should obtain the `submod`
                                            // bytes that can fit into the unused space in the last word
                                            // of the stored array. To get this, we read 32 bytes starting
                                            // from `submod`, so the data we read overlaps with the array
                                            // contents by `submod` bytes. Masking the lowest-order
                                            // `submod` bytes allows us to add that value directly to the
                                            // stored value.
                                            let submod := sub(32, slength)
                                            let mc := add(_postBytes, submod)
                                            let end := add(_postBytes, mlength)
                                            let mask := sub(exp(0x100, submod), 1)
                                            sstore(
                                                sc,
                                                add(
                                                    and(
                                                        fslot,
                                                        0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
                                                    ),
                                                    and(mload(mc), mask)
                                                )
                                            )
                                            for {
                                                mc := add(mc, 0x20)
                                                sc := add(sc, 1)
                                            } lt(mc, end) {
                                                sc := add(sc, 1)
                                                mc := add(mc, 0x20)
                                            } {
                                                sstore(sc, mload(mc))
                                            }
                                            mask := exp(0x100, sub(mc, end))
                                            sstore(sc, mul(div(mload(mc), mask), mask))
                                        }
                                        default {
                                            // get the keccak hash to get the contents of the array
                                            mstore(0x0, _preBytes_slot)
                                            // Start copying to the last used word of the stored array.
                                            let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                                            // save new length
                                            sstore(_preBytes_slot, add(mul(newlength, 2), 1))
                                            // Copy over the first `submod` bytes of the new data as in
                                            // case 1 above.
                                            let slengthmod := mod(slength, 32)
                                            let mlengthmod := mod(mlength, 32)
                                            let submod := sub(32, slengthmod)
                                            let mc := add(_postBytes, submod)
                                            let end := add(_postBytes, mlength)
                                            let mask := sub(exp(0x100, submod), 1)
                                            sstore(sc, add(sload(sc), and(mload(mc), mask)))
                                            
                                            for { 
                                                sc := add(sc, 1)
                                                mc := add(mc, 0x20)
                                            } lt(mc, end) {
                                                sc := add(sc, 1)
                                                mc := add(mc, 0x20)
                                            } {
                                                sstore(sc, mload(mc))
                                            }
                                            mask := exp(0x100, sub(mc, end))
                                            sstore(sc, mul(div(mload(mc), mask), mask))
                                        }
                                    }
                                }
                                function slice(bytes _bytes, uint _start, uint _length) internal  pure returns (bytes) {
                                    require(_bytes.length >= (_start + _length));
                                    bytes memory tempBytes;
                                    assembly {
                                        switch iszero(_length)
                                        case 0 {
                                            // Get a location of some free memory and store it in tempBytes as
                                            // Solidity does for memory variables.
                                            tempBytes := mload(0x40)
                                            // The first word of the slice result is potentially a partial
                                            // word read from the original array. To read it, we calculate
                                            // the length of that partial word and start copying that many
                                            // bytes into the array. The first word we copy will start with
                                            // data we don't care about, but the last `lengthmod` bytes will
                                            // land at the beginning of the contents of the new array. When
                                            // we're done copying, we overwrite the full first word with
                                            // the actual length of the slice.
                                            let lengthmod := and(_length, 31)
                                            // The multiplication in the next line is necessary
                                            // because when slicing multiples of 32 bytes (lengthmod == 0)
                                            // the following copy loop was copying the origin's length
                                            // and then ending prematurely not copying everything it should.
                                            let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                                            let end := add(mc, _length)
                                            for {
                                                // The multiplication in the next line has the same exact purpose
                                                // as the one above.
                                                let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                                            } lt(mc, end) {
                                                mc := add(mc, 0x20)
                                                cc := add(cc, 0x20)
                                            } {
                                                mstore(mc, mload(cc))
                                            }
                                            mstore(tempBytes, _length)
                                            //update free-memory pointer
                                            //allocating the array padded to 32 bytes like the compiler does now
                                            mstore(0x40, and(add(mc, 31), not(31)))
                                        }
                                        //if we want a zero-length slice let's just return a zero-length array
                                        default {
                                            tempBytes := mload(0x40)
                                            mstore(0x40, add(tempBytes, 0x20))
                                        }
                                    }
                                    return tempBytes;
                                }
                                function toAddress(bytes _bytes, uint _start) internal  pure returns (address) {
                                    require(_bytes.length >= (_start + 20));
                                    address tempAddress;
                                    assembly {
                                        tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
                                    }
                                    return tempAddress;
                                }
                                function toUint8(bytes _bytes, uint _start) internal  pure returns (uint8) {
                                    require(_bytes.length >= (_start + 1));
                                    uint8 tempUint;
                                    assembly {
                                        tempUint := mload(add(add(_bytes, 0x1), _start))
                                    }
                                    return tempUint;
                                }
                                function toUint16(bytes _bytes, uint _start) internal  pure returns (uint16) {
                                    require(_bytes.length >= (_start + 2));
                                    uint16 tempUint;
                                    assembly {
                                        tempUint := mload(add(add(_bytes, 0x2), _start))
                                    }
                                    return tempUint;
                                }
                                function toUint32(bytes _bytes, uint _start) internal  pure returns (uint32) {
                                    require(_bytes.length >= (_start + 4));
                                    uint32 tempUint;
                                    assembly {
                                        tempUint := mload(add(add(_bytes, 0x4), _start))
                                    }
                                    return tempUint;
                                }
                                function toUint(bytes _bytes, uint _start) internal  pure returns (uint256) {
                                    require(_bytes.length >= (_start + 32));
                                    uint256 tempUint;
                                    assembly {
                                        tempUint := mload(add(add(_bytes, 0x20), _start))
                                    }
                                    return tempUint;
                                }
                                function toBytes32(bytes _bytes, uint _start) internal  pure returns (bytes32) {
                                    require(_bytes.length >= (_start + 32));
                                    bytes32 tempBytes32;
                                    assembly {
                                        tempBytes32 := mload(add(add(_bytes, 0x20), _start))
                                    }
                                    return tempBytes32;
                                }
                                function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
                                    bool success = true;
                                    assembly {
                                        let length := mload(_preBytes)
                                        // if lengths don't match the arrays are not equal
                                        switch eq(length, mload(_postBytes))
                                        case 1 {
                                            // cb is a circuit breaker in the for loop since there's
                                            //  no said feature for inline assembly loops
                                            // cb = 1 - don't breaker
                                            // cb = 0 - break
                                            let cb := 1
                                            let mc := add(_preBytes, 0x20)
                                            let end := add(mc, length)
                                            for {
                                                let cc := add(_postBytes, 0x20)
                                            // the next line is the loop condition:
                                            // while(uint(mc < end) + cb == 2)
                                            } eq(add(lt(mc, end), cb), 2) {
                                                mc := add(mc, 0x20)
                                                cc := add(cc, 0x20)
                                            } {
                                                // if any of these checks fails then arrays are not equal
                                                if iszero(eq(mload(mc), mload(cc))) {
                                                    // unsuccess:
                                                    success := 0
                                                    cb := 0
                                                }
                                            }
                                        }
                                        default {
                                            // unsuccess:
                                            success := 0
                                        }
                                    }
                                    return success;
                                }
                                function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {
                                    bool success = true;
                                    assembly {
                                        // we know _preBytes_offset is 0
                                        let fslot := sload(_preBytes_slot)
                                        // Decode the length of the stored array like in concatStorage().
                                        let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                                        let mlength := mload(_postBytes)
                                        // if lengths don't match the arrays are not equal
                                        switch eq(slength, mlength)
                                        case 1 {
                                            // slength can contain both the length and contents of the array
                                            // if length < 32 bytes so let's prepare for that
                                            // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                                            if iszero(iszero(slength)) {
                                                switch lt(slength, 32)
                                                case 1 {
                                                    // blank the last byte which is the length
                                                    fslot := mul(div(fslot, 0x100), 0x100)
                                                    if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
                                                        // unsuccess:
                                                        success := 0
                                                    }
                                                }
                                                default {
                                                    // cb is a circuit breaker in the for loop since there's
                                                    //  no said feature for inline assembly loops
                                                    // cb = 1 - don't breaker
                                                    // cb = 0 - break
                                                    let cb := 1
                                                    // get the keccak hash to get the contents of the array
                                                    mstore(0x0, _preBytes_slot)
                                                    let sc := keccak256(0x0, 0x20)
                                                    let mc := add(_postBytes, 0x20)
                                                    let end := add(mc, mlength)
                                                    // the next line is the loop condition:
                                                    // while(uint(mc < end) + cb == 2)
                                                    for {} eq(add(lt(mc, end), cb), 2) {
                                                        sc := add(sc, 1)
                                                        mc := add(mc, 0x20)
                                                    } {
                                                        if iszero(eq(sload(sc), mload(mc))) {
                                                            // unsuccess:
                                                            success := 0
                                                            cb := 0
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        default {
                                            // unsuccess:
                                            success := 0
                                        }
                                    }
                                    return success;
                                }
                            }
                            // SPDX-FileCopyrightText: 2020 Lido <[email protected]>
                            // SPDX-License-Identifier: GPL-3.0
                            pragma solidity 0.4.24;
                            /**
                              * @title Liquid staking pool
                              *
                              * For the high-level description of the pool operation please refer to the paper.
                              * Pool manages withdrawal keys and fees. It receives ether submitted by users on the ETH 1 side
                              * and stakes it via the deposit_contract.sol contract. It doesn't hold ether on it's balance,
                              * only a small portion (buffer) of it.
                              * It also mints new tokens for rewards generated at the ETH 2.0 side.
                              */
                            interface ILido {
                                /**
                                  * @notice Stop pool routine operations
                                  */
                                function stop() external;
                                /**
                                  * @notice Resume pool routine operations
                                  */
                                function resume() external;
                                event Stopped();
                                event Resumed();
                                /**
                                  * @notice Set fee rate to `_feeBasisPoints` basis points. The fees are accrued when oracles report staking results
                                  * @param _feeBasisPoints Fee rate, in basis points
                                  */
                                function setFee(uint16 _feeBasisPoints) external;
                                /**
                                  * @notice Set fee distribution: `_treasuryFeeBasisPoints` basis points go to the treasury, `_insuranceFeeBasisPoints` basis points go to the insurance fund, `_operatorsFeeBasisPoints` basis points go to node operators. The sum has to be 10 000.
                                  */
                                function setFeeDistribution(
                                    uint16 _treasuryFeeBasisPoints,
                                    uint16 _insuranceFeeBasisPoints,
                                    uint16 _operatorsFeeBasisPoints)
                                    external;
                                /**
                                  * @notice Returns staking rewards fee rate
                                  */
                                function getFee() external view returns (uint16 feeBasisPoints);
                                /**
                                  * @notice Returns fee distribution proportion
                                  */
                                function getFeeDistribution() external view returns (uint16 treasuryFeeBasisPoints, uint16 insuranceFeeBasisPoints,
                                                                                     uint16 operatorsFeeBasisPoints);
                                event FeeSet(uint16 feeBasisPoints);
                                event FeeDistributionSet(uint16 treasuryFeeBasisPoints, uint16 insuranceFeeBasisPoints, uint16 operatorsFeeBasisPoints);
                                /**
                                  * @notice Set credentials to withdraw ETH on ETH 2.0 side after the phase 2 is launched to `_withdrawalCredentials`
                                  * @dev Note that setWithdrawalCredentials discards all unused signing keys as the signatures are invalidated.
                                  * @param _withdrawalCredentials hash of withdrawal multisignature key as accepted by
                                  *        the deposit_contract.deposit function
                                  */
                                function setWithdrawalCredentials(bytes32 _withdrawalCredentials) external;
                                /**
                                  * @notice Returns current credentials to withdraw ETH on ETH 2.0 side after the phase 2 is launched
                                  */
                                function getWithdrawalCredentials() external view returns (bytes);
                                event WithdrawalCredentialsSet(bytes32 withdrawalCredentials);
                                /**
                                  * @notice Ether on the ETH 2.0 side reported by the oracle
                                  * @param _epoch Epoch id
                                  * @param _eth2balance Balance in wei on the ETH 2.0 side
                                  */
                                function pushBeacon(uint256 _epoch, uint256 _eth2balance) external;
                                // User functions
                                /**
                                  * @notice Adds eth to the pool
                                  * @return StETH Amount of StETH generated
                                  */
                                function submit(address _referral) external payable returns (uint256 StETH);
                                // Records a deposit made by a user
                                event Submitted(address indexed sender, uint256 amount, address referral);
                                // The `_amount` of ether was sent to the deposit_contract.deposit function.
                                event Unbuffered(uint256 amount);
                                /**
                                  * @notice Issues withdrawal request. Large withdrawals will be processed only after the phase 2 launch.
                                  * @param _amount Amount of StETH to burn
                                  * @param _pubkeyHash Receiving address
                                  */
                                function withdraw(uint256 _amount, bytes32 _pubkeyHash) external;
                                // Requested withdrawal of `etherAmount` to `pubkeyHash` on the ETH 2.0 side, `tokenAmount` burned by `sender`,
                                // `sentFromBuffer` was sent on the current Ethereum side.
                                event Withdrawal(address indexed sender, uint256 tokenAmount, uint256 sentFromBuffer,
                                                 bytes32 indexed pubkeyHash, uint256 etherAmount);
                                // Info functions
                                /**
                                  * @notice Gets the amount of Ether controlled by the system
                                  */
                                function getTotalPooledEther() external view returns (uint256);
                                /**
                                  * @notice Gets the amount of Ether temporary buffered on this contract balance
                                  */
                                function getBufferedEther() external view returns (uint256);
                                /**
                                  * @notice Returns the key values related to Beacon-side
                                  * @return depositedValidators - number of deposited validators
                                  * @return beaconValidators - number of Lido's validators visible in the Beacon state, reported by oracles
                                  * @return beaconBalance - total amount of Beacon-side Ether (sum of all the balances of Lido validators)
                                  */
                                function getBeaconStat() external view returns (uint256 depositedValidators, uint256 beaconValidators, uint256 beaconBalance);
                            }
                            // SPDX-FileCopyrightText: 2020 Lido <[email protected]>
                            // SPDX-License-Identifier: GPL-3.0
                            pragma solidity 0.4.24;
                            /**
                              * @title Node Operator registry
                              *
                              * Node Operator registry manages signing keys and other node operator data.
                              * It's also responsible for distributing rewards to node operators.
                              */
                            interface INodeOperatorsRegistry {
                                /**
                                  * @notice Add node operator named `name` with reward address `rewardAddress` and staking limit `stakingLimit` validators
                                  * @param _name Human-readable name
                                  * @param _rewardAddress Ethereum 1 address which receives stETH rewards for this operator
                                  * @param _stakingLimit the maximum number of validators to stake for this operator
                                  * @return a unique key of the added operator
                                  */
                                function addNodeOperator(string _name, address _rewardAddress, uint64 _stakingLimit) external returns (uint256 id);
                                /**
                                  * @notice `_active ? 'Enable' : 'Disable'` the node operator #`_id`
                                  */
                                function setNodeOperatorActive(uint256 _id, bool _active) external;
                                /**
                                  * @notice Change human-readable name of the node operator #`_id` to `_name`
                                  */
                                function setNodeOperatorName(uint256 _id, string _name) external;
                                /**
                                  * @notice Change reward address of the node operator #`_id` to `_rewardAddress`
                                  */
                                function setNodeOperatorRewardAddress(uint256 _id, address _rewardAddress) external;
                                /**
                                  * @notice Set the maximum number of validators to stake for the node operator #`_id` to `_stakingLimit`
                                  */
                                function setNodeOperatorStakingLimit(uint256 _id, uint64 _stakingLimit) external;
                                /**
                                  * @notice Report `_stoppedIncrement` more stopped validators of the node operator #`_id`
                                  */
                                function reportStoppedValidators(uint256 _id, uint64 _stoppedIncrement) external;
                                /**
                                  * @notice Remove unused signing keys
                                  * @dev Function is used by the pool
                                  */
                                function trimUnusedKeys() external;
                                /**
                                  * @notice Returns total number of node operators
                                  */
                                function getNodeOperatorsCount() external view returns (uint256);
                                /**
                                  * @notice Returns number of active node operators
                                  */
                                function getActiveNodeOperatorsCount() external view returns (uint256);
                                /**
                                  * @notice Returns the n-th node operator
                                  * @param _id Node Operator id
                                  * @param _fullInfo If true, name will be returned as well
                                  */
                                function getNodeOperator(uint256 _id, bool _fullInfo) external view returns (
                                    bool active,
                                    string name,
                                    address rewardAddress,
                                    uint64 stakingLimit,
                                    uint64 stoppedValidators,
                                    uint64 totalSigningKeys,
                                    uint64 usedSigningKeys);
                                /**
                                  * @notice Returns the rewards distribution proportional to the effective stake for each node operator.
                                  * @param _totalRewardShares Total amount of reward shares to distribute.
                                  */
                                function getRewardsDistribution(uint256 _totalRewardShares) external view returns (
                                    address[] memory recipients,
                                    uint256[] memory shares
                                );
                                event NodeOperatorAdded(uint256 id, string name, address rewardAddress, uint64 stakingLimit);
                                event NodeOperatorActiveSet(uint256 indexed id, bool active);
                                event NodeOperatorNameSet(uint256 indexed id, string name);
                                event NodeOperatorRewardAddressSet(uint256 indexed id, address rewardAddress);
                                event NodeOperatorStakingLimitSet(uint256 indexed id, uint64 stakingLimit);
                                event NodeOperatorTotalStoppedValidatorsReported(uint256 indexed id, uint64 totalStopped);
                                /**
                                 * @notice Selects and returns at most `_numKeys` signing keys (as well as the corresponding
                                 *         signatures) from the set of active keys and marks the selected keys as used.
                                 *         May only be called by the pool contract.
                                 *
                                 * @param _numKeys The number of keys to select. The actual number of selected keys may be less
                                 *        due to the lack of active keys.
                                 */
                                function assignNextSigningKeys(uint256 _numKeys) external returns (bytes memory pubkeys, bytes memory signatures);
                                /**
                                  * @notice Add `_quantity` validator signing keys to the keys of the node operator #`_operator_id`. Concatenated keys are: `_pubkeys`
                                  * @dev Along with each key the DAO has to provide a signatures for the
                                  *      (pubkey, withdrawal_credentials, 32000000000) message.
                                  *      Given that information, the contract'll be able to call
                                  *      deposit_contract.deposit on-chain.
                                  * @param _operator_id Node Operator id
                                  * @param _quantity Number of signing keys provided
                                  * @param _pubkeys Several concatenated validator signing keys
                                  * @param _signatures Several concatenated signatures for (pubkey, withdrawal_credentials, 32000000000) messages
                                  */
                                function addSigningKeys(uint256 _operator_id, uint256 _quantity, bytes _pubkeys, bytes _signatures) external;
                                /**
                                  * @notice Removes a validator signing key #`_index` from the keys of the node operator #`_operator_id`
                                  * @param _operator_id Node Operator id
                                  * @param _index Index of the key, starting with 0
                                  */
                                function removeSigningKey(uint256 _operator_id, uint256 _index) external;
                                /**
                                  * @notice Returns total number of signing keys of the node operator #`_operator_id`
                                  */
                                function getTotalSigningKeyCount(uint256 _operator_id) external view returns (uint256);
                                /**
                                  * @notice Returns number of usable signing keys of the node operator #`_operator_id`
                                  */
                                function getUnusedSigningKeyCount(uint256 _operator_id) external view returns (uint256);
                                /**
                                  * @notice Returns n-th signing key of the node operator #`_operator_id`
                                  * @param _operator_id Node Operator id
                                  * @param _index Index of the key, starting with 0
                                  * @return key Key
                                  * @return depositSignature Signature needed for a deposit_contract.deposit call
                                  * @return used Flag indication if the key was used in the staking
                                  */
                                function getSigningKey(uint256 _operator_id, uint256 _index) external view returns
                                        (bytes key, bytes depositSignature, bool used);
                                event SigningKeyAdded(uint256 indexed operatorId, bytes pubkey);
                                event SigningKeyRemoved(uint256 indexed operatorId, bytes pubkey);
                            }
                            // SPDX-FileCopyrightText: 2020 Lido <[email protected]>
                            // SPDX-License-Identifier: GPL-3.0
                            /* See contracts/COMPILERS.md */
                            pragma solidity 0.4.24;
                            import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
                            import "@aragon/os/contracts/common/UnstructuredStorage.sol";
                            import "@aragon/os/contracts/lib/math/SafeMath.sol";
                            import "./lib/Pausable.sol";
                            /**
                             * @title Interest-bearing ERC20-like token for Lido Liquid Stacking protocol.
                             *
                             * This contract is abstract. To make the contract deployable override the
                             * `_getTotalPooledEther` function. `Lido.sol` contract inherits StETH and defines
                             * the `_getTotalPooledEther` function.
                             *
                             * StETH balances are dynamic and represent the holder's share in the total amount
                             * of Ether controlled by the protocol. Account shares aren't normalized, so the
                             * contract also stores the sum of all shares to calculate each account's token balance
                             * which equals to:
                             *
                             *   shares[account] * _getTotalPooledEther() / _getTotalShares()
                             *
                             * For example, assume that we have:
                             *
                             *   _getTotalPooledEther() -> 10 ETH
                             *   sharesOf(user1) -> 100
                             *   sharesOf(user2) -> 400
                             *
                             * Therefore:
                             *
                             *   balanceOf(user1) -> 2 tokens which corresponds 2 ETH
                             *   balanceOf(user2) -> 8 tokens which corresponds 8 ETH
                             *
                             * Since balances of all token holders change when the amount of total pooled Ether
                             * changes, this token cannot fully implement ERC20 standard: it only emits `Transfer`
                             * events upon explicit transfer between holders. In contrast, when total amount of
                             * pooled Ether increases, no `Transfer` events are generated: doing so would require
                             * emitting an event for each token holder and thus running an unbounded loop.
                             *
                             * The token inherits from `Pausable` and uses `whenNotStopped` modifier for methods
                             * which change `shares` or `allowances`. `_stop` and `_resume` functions are overriden
                             * in `Lido.sol` and might be called by an account with the `PAUSE_ROLE` assigned by the
                             * DAO. This is useful for emergency scenarios, e.g. a protocol bug, where one might want
                             * to freeze all token transfers and approvals until the emergency is resolved.
                             */
                            contract StETH is IERC20, Pausable {
                                using SafeMath for uint256;
                                using UnstructuredStorage for bytes32;
                                /**
                                 * @dev StETH balances are dynamic and are calculated based on the accounts' shares
                                 * and the total amount of Ether controlled by the protocol. Account shares aren't
                                 * normalized, so the contract also stores the sum of all shares to calculate
                                 * each account's token balance which equals to:
                                 *
                                 *   shares[account] * _getTotalPooledEther() / _getTotalShares()
                                */
                                mapping (address => uint256) private shares;
                                /**
                                 * @dev Allowances are nominated in tokens, not token shares.
                                 */
                                mapping (address => mapping (address => uint256)) private allowances;
                                /**
                                 * @dev Storage position used for holding the total amount of shares in existence.
                                 *
                                 * The Lido protocol is built on top of Aragon and uses the Unstructured Storage pattern
                                 * for value types:
                                 *
                                 * https://blog.openzeppelin.com/upgradeability-using-unstructured-storage
                                 * https://blog.8bitzen.com/posts/20-02-2020-understanding-how-solidity-upgradeable-unstructured-proxies-work
                                 *
                                 * For reference types, conventional storage variables are used since it's non-trivial
                                 * and error-prone to implement reference-type unstructured storage using Solidity v0.4;
                                 * see https://github.com/lidofinance/lido-dao/issues/181#issuecomment-736098834
                                 */
                                bytes32 internal constant TOTAL_SHARES_POSITION = keccak256("lido.StETH.totalShares");
                                /**
                                 * @return the name of the token.
                                 */
                                function name() public pure returns (string) {
                                    return "Liquid staked Ether 2.0";
                                }
                                /**
                                 * @return the symbol of the token, usually a shorter version of the
                                 * name.
                                 */
                                function symbol() public pure returns (string) {
                                    return "stETH";
                                }
                                /**
                                 * @return the number of decimals for getting user representation of a token amount.
                                 */
                                function decimals() public pure returns (uint8) {
                                    return 18;
                                }
                                /**
                                 * @return the amount of tokens in existence.
                                 *
                                 * @dev Always equals to `_getTotalPooledEther()` since token amount
                                 * is pegged to the total amount of Ether controlled by the protocol.
                                 */
                                function totalSupply() public view returns (uint256) {
                                    return _getTotalPooledEther();
                                }
                                /**
                                 * @return the entire amount of Ether controlled by the protocol.
                                 *
                                 * @dev The sum of all ETH balances in the protocol, equals to the total supply of stETH.
                                 */
                                function getTotalPooledEther() public view returns (uint256) {
                                    return _getTotalPooledEther();
                                }
                                /**
                                 * @return the amount of tokens owned by the `_account`.
                                 *
                                 * @dev Balances are dynamic and equal the `_account`'s share in the amount of the
                                 * total Ether controlled by the protocol. See `sharesOf`.
                                 */
                                function balanceOf(address _account) public view returns (uint256) {
                                    return getPooledEthByShares(_sharesOf(_account));
                                }
                                /**
                                 * @notice Moves `_amount` tokens from the caller's account to the `_recipient` account.
                                 *
                                 * @return a boolean value indicating whether the operation succeeded.
                                 * Emits a `Transfer` event.
                                 *
                                 * Requirements:
                                 *
                                 * - `_recipient` cannot be the zero address.
                                 * - the caller must have a balance of at least `_amount`.
                                 * - the contract must not be paused.
                                 *
                                 * @dev The `_amount` argument is the amount of tokens, not shares.
                                 */
                                function transfer(address _recipient, uint256 _amount) public returns (bool) {
                                    _transfer(msg.sender, _recipient, _amount);
                                    return true;
                                }
                                /**
                                 * @return the remaining number of tokens that `_spender` is allowed to spend
                                 * on behalf of `_owner` through `transferFrom`. This is zero by default.
                                 *
                                 * @dev This value changes when `approve` or `transferFrom` is called.
                                 */
                                function allowance(address _owner, address _spender) public view returns (uint256) {
                                    return allowances[_owner][_spender];
                                }
                                /**
                                 * @notice Sets `_amount` as the allowance of `_spender` over the caller's tokens.
                                 *
                                 * @return a boolean value indicating whether the operation succeeded.
                                 * Emits an `Approval` event.
                                 *
                                 * Requirements:
                                 *
                                 * - `_spender` cannot be the zero address.
                                 * - the contract must not be paused.
                                 *
                                 * @dev The `_amount` argument is the amount of tokens, not shares.
                                 */
                                function approve(address _spender, uint256 _amount) public returns (bool) {
                                    _approve(msg.sender, _spender, _amount);
                                    return true;
                                }
                                /**
                                 * @notice Moves `_amount` tokens from `_sender` to `_recipient` using the
                                 * allowance mechanism. `_amount` is then deducted from the caller's
                                 * allowance.
                                 *
                                 * @return a boolean value indicating whether the operation succeeded.
                                 *
                                 * Emits a `Transfer` event.
                                 * Emits an `Approval` event indicating the updated allowance.
                                 *
                                 * Requirements:
                                 *
                                 * - `_sender` and `_recipient` cannot be the zero addresses.
                                 * - `_sender` must have a balance of at least `_amount`.
                                 * - the caller must have allowance for `_sender`'s tokens of at least `_amount`.
                                 * - the contract must not be paused.
                                 *
                                 * @dev The `_amount` argument is the amount of tokens, not shares.
                                 */
                                function transferFrom(address _sender, address _recipient, uint256 _amount) public returns (bool) {
                                    uint256 currentAllowance = allowances[_sender][msg.sender];
                                    require(currentAllowance >= _amount, "TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE");
                                    _transfer(_sender, _recipient, _amount);
                                    _approve(_sender, msg.sender, currentAllowance.sub(_amount));
                                    return true;
                                }
                                /**
                                 * @notice Atomically increases the allowance granted to `_spender` by the caller by `_addedValue`.
                                 *
                                 * This is an alternative to `approve` that can be used as a mitigation for
                                 * problems described in:
                                 * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol#L42
                                 * Emits an `Approval` event indicating the updated allowance.
                                 *
                                 * Requirements:
                                 *
                                 * - `_spender` cannot be the the zero address.
                                 * - the contract must not be paused.
                                 */
                                function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
                                    _approve(msg.sender, _spender, allowances[msg.sender][_spender].add(_addedValue));
                                    return true;
                                }
                                /**
                                 * @notice Atomically decreases the allowance granted to `_spender` by the caller by `_subtractedValue`.
                                 *
                                 * This is an alternative to `approve` that can be used as a mitigation for
                                 * problems described in:
                                 * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol#L42
                                 * Emits an `Approval` event indicating the updated allowance.
                                 *
                                 * Requirements:
                                 *
                                 * - `_spender` cannot be the zero address.
                                 * - `_spender` must have allowance for the caller of at least `_subtractedValue`.
                                 * - the contract must not be paused.
                                 */
                                function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
                                    uint256 currentAllowance = allowances[msg.sender][_spender];
                                    require(currentAllowance >= _subtractedValue, "DECREASED_ALLOWANCE_BELOW_ZERO");
                                    _approve(msg.sender, _spender, currentAllowance.sub(_subtractedValue));
                                    return true;
                                }
                                /**
                                 * @return the total amount of shares in existence.
                                 *
                                 * @dev The sum of all accounts' shares can be an arbitrary number, therefore
                                 * it is necessary to store it in order to calculate each account's relative share.
                                 */
                                function getTotalShares() public view returns (uint256) {
                                    return _getTotalShares();
                                }
                                /**
                                 * @return the amount of shares owned by `_account`.
                                 */
                                function sharesOf(address _account) public view returns (uint256) {
                                    return _sharesOf(_account);
                                }
                                /**
                                 * @return the amount of shares that corresponds to `_ethAmount` protocol-controlled Ether.
                                 */
                                function getSharesByPooledEth(uint256 _ethAmount) public view returns (uint256) {
                                    uint256 totalPooledEther = _getTotalPooledEther();
                                    if (totalPooledEther == 0) {
                                        return 0;
                                    } else {
                                        return _ethAmount
                                            .mul(_getTotalShares())
                                            .div(totalPooledEther);
                                    }
                                }
                                /**
                                 * @return the amount of Ether that corresponds to `_sharesAmount` token shares.
                                 */
                                function getPooledEthByShares(uint256 _sharesAmount) public view returns (uint256) {
                                    uint256 totalShares = _getTotalShares();
                                    if (totalShares == 0) {
                                        return 0;
                                    } else {
                                        return _sharesAmount
                                            .mul(_getTotalPooledEther())
                                            .div(totalShares);
                                    }
                                }
                                /**
                                 * @return the total amount (in wei) of Ether controlled by the protocol.
                                 * @dev This is used for calaulating tokens from shares and vice versa.
                                 * @dev This function is required to be implemented in a derived contract.
                                 */
                                function _getTotalPooledEther() internal view returns (uint256);
                                /**
                                 * @notice Moves `_amount` tokens from `_sender` to `_recipient`.
                                 * Emits a `Transfer` event.
                                 */
                                function _transfer(address _sender, address _recipient, uint256 _amount) internal {
                                    uint256 _sharesToTransfer = getSharesByPooledEth(_amount);
                                    _transferShares(_sender, _recipient, _sharesToTransfer);
                                    emit Transfer(_sender, _recipient, _amount);
                                }
                                /**
                                 * @notice Sets `_amount` as the allowance of `_spender` over the `_owner` s tokens.
                                 *
                                 * Emits an `Approval` event.
                                 *
                                 * Requirements:
                                 *
                                 * - `_owner` cannot be the zero address.
                                 * - `_spender` cannot be the zero address.
                                 * - the contract must not be paused.
                                 */
                                function _approve(address _owner, address _spender, uint256 _amount) internal whenNotStopped {
                                    require(_owner != address(0), "APPROVE_FROM_ZERO_ADDRESS");
                                    require(_spender != address(0), "APPROVE_TO_ZERO_ADDRESS");
                                    allowances[_owner][_spender] = _amount;
                                    emit Approval(_owner, _spender, _amount);
                                }
                                /**
                                 * @return the total amount of shares in existence.
                                 */
                                function _getTotalShares() internal view returns (uint256) {
                                    return TOTAL_SHARES_POSITION.getStorageUint256();
                                }
                                /**
                                 * @return the amount of shares owned by `_account`.
                                 */
                                function _sharesOf(address _account) internal view returns (uint256) {
                                    return shares[_account];
                                }
                                /**
                                 * @notice Moves `_sharesAmount` shares from `_sender` to `_recipient`.
                                 *
                                 * Requirements:
                                 *
                                 * - `_sender` cannot be the zero address.
                                 * - `_recipient` cannot be the zero address.
                                 * - `_sender` must hold at least `_sharesAmount` shares.
                                 * - the contract must not be paused.
                                 */
                                function _transferShares(address _sender, address _recipient, uint256 _sharesAmount) internal whenNotStopped {
                                    require(_sender != address(0), "TRANSFER_FROM_THE_ZERO_ADDRESS");
                                    require(_recipient != address(0), "TRANSFER_TO_THE_ZERO_ADDRESS");
                                    uint256 currentSenderShares = shares[_sender];
                                    require(_sharesAmount <= currentSenderShares, "TRANSFER_AMOUNT_EXCEEDS_BALANCE");
                                    shares[_sender] = currentSenderShares.sub(_sharesAmount);
                                    shares[_recipient] = shares[_recipient].add(_sharesAmount);
                                }
                                /**
                                 * @notice Creates `_sharesAmount` shares and assigns them to `_recipient`, increasing the total amount of shares.
                                 * @dev This doesn't increase the token total supply.
                                 *
                                 * Requirements:
                                 *
                                 * - `_recipient` cannot be the zero address.
                                 * - the contract must not be paused.
                                 */
                                function _mintShares(address _recipient, uint256 _sharesAmount) internal whenNotStopped returns (uint256 newTotalShares) {
                                    require(_recipient != address(0), "MINT_TO_THE_ZERO_ADDRESS");
                                    newTotalShares = _getTotalShares().add(_sharesAmount);
                                    TOTAL_SHARES_POSITION.setStorageUint256(newTotalShares);
                                    shares[_recipient] = shares[_recipient].add(_sharesAmount);
                                    // Notice: we're not emitting a Transfer event from the zero address here since shares mint
                                    // works by taking the amount of tokens corresponding to the minted shares from all other
                                    // token holders, proportionally to their share. The total supply of the token doesn't change
                                    // as the result. This is equivalent to performing a send from each other token holder's
                                    // address to `address`, but we cannot reflect this as it would require sending an unbounded
                                    // number of events.
                                }
                                /**
                                 * @notice Destroys `_sharesAmount` shares from `_account`'s holdings, decreasing the total amount of shares.
                                 * @dev This doesn't decrease the token total supply.
                                 *
                                 * Requirements:
                                 *
                                 * - `_account` cannot be the zero address.
                                 * - `_account` must hold at least `_sharesAmount` shares.
                                 * - the contract must not be paused.
                                 */
                                function _burnShares(address _account, uint256 _sharesAmount) internal whenNotStopped returns (uint256 newTotalShares) {
                                    require(_account != address(0), "BURN_FROM_THE_ZERO_ADDRESS");
                                    uint256 accountShares = shares[_account];
                                    require(_sharesAmount <= accountShares, "BURN_AMOUNT_EXCEEDS_BALANCE");
                                    newTotalShares = _getTotalShares().sub(_sharesAmount);
                                    TOTAL_SHARES_POSITION.setStorageUint256(newTotalShares);
                                    shares[_account] = accountShares.sub(_sharesAmount);
                                    // Notice: we're not emitting a Transfer event to the zero address here since shares burn
                                    // works by redistributing the amount of tokens corresponding to the burned shares between
                                    // all other token holders. The total supply of the token doesn't change as the result.
                                    // This is equivalent to performing a send from `address` to each other token holder address,
                                    // but we cannot reflect this as it would require sending an unbounded number of events.
                                }
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            import "../common/UnstructuredStorage.sol";
                            import "../kernel/IKernel.sol";
                            contract AppStorage {
                                using UnstructuredStorage for bytes32;
                                /* Hardcoded constants to save gas
                                bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
                                bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
                                */
                                bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
                                bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
                                function kernel() public view returns (IKernel) {
                                    return IKernel(KERNEL_POSITION.getStorageAddress());
                                }
                                function appId() public view returns (bytes32) {
                                    return APP_ID_POSITION.getStorageBytes32();
                                }
                                function setKernel(IKernel _kernel) internal {
                                    KERNEL_POSITION.setStorageAddress(address(_kernel));
                                }
                                function setAppId(bytes32 _appId) internal {
                                    APP_ID_POSITION.setStorageBytes32(_appId);
                                }
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            contract ACLSyntaxSugar {
                                function arr() internal pure returns (uint256[]) {
                                    return new uint256[](0);
                                }
                                function arr(bytes32 _a) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a));
                                }
                                function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b));
                                }
                                function arr(address _a) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a));
                                }
                                function arr(address _a, address _b) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b));
                                }
                                function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), _b, _c);
                                }
                                function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), _b, _c, _d);
                                }
                                function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b));
                                }
                                function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b), _c, _d, _e);
                                }
                                function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b), uint256(_c));
                                }
                                function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
                                    return arr(uint256(_a), uint256(_b), uint256(_c));
                                }
                                function arr(uint256 _a) internal pure returns (uint256[] r) {
                                    r = new uint256[](1);
                                    r[0] = _a;
                                }
                                function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
                                    r = new uint256[](2);
                                    r[0] = _a;
                                    r[1] = _b;
                                }
                                function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
                                    r = new uint256[](3);
                                    r[0] = _a;
                                    r[1] = _b;
                                    r[2] = _c;
                                }
                                function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
                                    r = new uint256[](4);
                                    r[0] = _a;
                                    r[1] = _b;
                                    r[2] = _c;
                                    r[3] = _d;
                                }
                                function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
                                    r = new uint256[](5);
                                    r[0] = _a;
                                    r[1] = _b;
                                    r[2] = _c;
                                    r[3] = _d;
                                    r[4] = _e;
                                }
                            }
                            contract ACLHelpers {
                                function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
                                    return uint8(_x >> (8 * 30));
                                }
                                function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
                                    return uint8(_x >> (8 * 31));
                                }
                                function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
                                    a = uint32(_x);
                                    b = uint32(_x >> (8 * 4));
                                    c = uint32(_x >> (8 * 8));
                                }
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            import "./Petrifiable.sol";
                            contract Autopetrified is Petrifiable {
                                constructor() public {
                                    // Immediately petrify base (non-proxy) instances of inherited contracts on deploy.
                                    // This renders them uninitializable (and unusable without a proxy).
                                    petrify();
                                }
                            }
                            pragma solidity ^0.4.24;
                            library ConversionHelpers {
                                string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
                                function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
                                    // Force cast the uint256[] into a bytes array, by overwriting its length
                                    // Note that the bytes array doesn't need to be initialized as we immediately overwrite it
                                    // with the input and a new length. The input becomes invalid from this point forward.
                                    uint256 byteLength = _input.length * 32;
                                    assembly {
                                        output := _input
                                        mstore(output, byteLength)
                                    }
                                }
                                function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
                                    // Force cast the bytes array into a uint256[], by overwriting its length
                                    // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
                                    // with the input and a new length. The input becomes invalid from this point forward.
                                    uint256 intsLength = _input.length / 32;
                                    require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
                                    assembly {
                                        output := _input
                                        mstore(output, intsLength)
                                    }
                                }
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            import "../common/UnstructuredStorage.sol";
                            contract ReentrancyGuard {
                                using UnstructuredStorage for bytes32;
                                /* Hardcoded constants to save gas
                                bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex");
                                */
                                bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb;
                                string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL";
                                modifier nonReentrant() {
                                    // Ensure mutex is unlocked
                                    require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT);
                                    // Lock mutex before function call
                                    REENTRANCY_MUTEX_POSITION.setStorageBool(true);
                                    // Perform function call
                                    _;
                                    // Unlock mutex after function call
                                    REENTRANCY_MUTEX_POSITION.setStorageBool(false);
                                }
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            import "../lib/token/ERC20.sol";
                            import "./EtherTokenConstant.sol";
                            import "./IsContract.sol";
                            import "./IVaultRecoverable.sol";
                            import "./SafeERC20.sol";
                            contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
                                using SafeERC20 for ERC20;
                                string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
                                string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
                                string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
                                /**
                                 * @notice Send funds to recovery Vault. This contract should never receive funds,
                                 *         but in case it does, this function allows one to recover them.
                                 * @param _token Token balance to be sent to recovery vault.
                                 */
                                function transferToVault(address _token) external {
                                    require(allowRecoverability(_token), ERROR_DISALLOWED);
                                    address vault = getRecoveryVault();
                                    require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
                                    uint256 balance;
                                    if (_token == ETH) {
                                        balance = address(this).balance;
                                        vault.transfer(balance);
                                    } else {
                                        ERC20 token = ERC20(_token);
                                        balance = token.staticBalanceOf(this);
                                        require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
                                    }
                                    emit RecoverToVault(vault, _token, balance);
                                }
                                /**
                                * @dev By default deriving from AragonApp makes it recoverable
                                * @param token Token address that would be recovered
                                * @return bool whether the app allows the recovery
                                */
                                function allowRecoverability(address token) public view returns (bool) {
                                    return true;
                                }
                                // Cast non-implemented interface to be public so we can use it internally
                                function getRecoveryVault() public view returns (address);
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            import "./IEVMScriptExecutor.sol";
                            import "./IEVMScriptRegistry.sol";
                            import "../apps/AppStorage.sol";
                            import "../kernel/KernelConstants.sol";
                            import "../common/Initializable.sol";
                            contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants {
                                string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE";
                                string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED";
                                /* This is manually crafted in assembly
                                string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN";
                                */
                                event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData);
                                function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
                                    return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script));
                                }
                                function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) {
                                    address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID);
                                    return IEVMScriptRegistry(registryAddr);
                                }
                                function runScript(bytes _script, bytes _input, address[] _blacklist)
                                    internal
                                    isInitialized
                                    protectState
                                    returns (bytes)
                                {
                                    IEVMScriptExecutor executor = getEVMScriptExecutor(_script);
                                    require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE);
                                    bytes4 sig = executor.execScript.selector;
                                    bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist);
                                    bytes memory output;
                                    assembly {
                                        let success := delegatecall(
                                            gas,                // forward all gas
                                            executor,           // address
                                            add(data, 0x20),    // calldata start
                                            mload(data),        // calldata length
                                            0,                  // don't write output (we'll handle this ourselves)
                                            0                   // don't write output
                                        )
                                        output := mload(0x40) // free mem ptr get
                                        switch success
                                        case 0 {
                                            // If the call errored, forward its full error data
                                            returndatacopy(output, 0, returndatasize)
                                            revert(output, returndatasize)
                                        }
                                        default {
                                            switch gt(returndatasize, 0x3f)
                                            case 0 {
                                                // Need at least 0x40 bytes returned for properly ABI-encoded bytes values,
                                                // revert with "EVMRUN_EXECUTOR_INVALID_RETURN"
                                                // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in
                                                // this memory layout
                                                mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000)         // error identifier
                                                mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
                                                mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length
                                                mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason
                                                revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
                                            }
                                            default {
                                                // Copy result
                                                //
                                                // Needs to perform an ABI decode for the expected `bytes` return type of
                                                // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as:
                                                //    [ position of the first dynamic length return value = 0x20 (32 bytes) ]
                                                //    [ output length (32 bytes) ]
                                                //    [ output content (N bytes) ]
                                                //
                                                // Perform the ABI decode by ignoring the first 32 bytes of the return data
                                                let copysize := sub(returndatasize, 0x20)
                                                returndatacopy(output, 0x20, copysize)
                                                mstore(0x40, add(output, copysize)) // free mem ptr set
                                            }
                                        }
                                    }
                                    emit ScriptResult(address(executor), _script, _input, output);
                                    return output;
                                }
                                modifier protectState {
                                    address preKernel = address(kernel());
                                    bytes32 preAppId = appId();
                                    _; // exec
                                    require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED);
                                    require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED);
                                }
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            library UnstructuredStorage {
                                function getStorageBool(bytes32 position) internal view returns (bool data) {
                                    assembly { data := sload(position) }
                                }
                                function getStorageAddress(bytes32 position) internal view returns (address data) {
                                    assembly { data := sload(position) }
                                }
                                function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
                                    assembly { data := sload(position) }
                                }
                                function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
                                    assembly { data := sload(position) }
                                }
                                function setStorageBool(bytes32 position, bool data) internal {
                                    assembly { sstore(position, data) }
                                }
                                function setStorageAddress(bytes32 position, address data) internal {
                                    assembly { sstore(position, data) }
                                }
                                function setStorageBytes32(bytes32 position, bytes32 data) internal {
                                    assembly { sstore(position, data) }
                                }
                                function setStorageUint256(bytes32 position, uint256 data) internal {
                                    assembly { sstore(position, data) }
                                }
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            import "../acl/IACL.sol";
                            import "../common/IVaultRecoverable.sol";
                            interface IKernelEvents {
                                event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
                            }
                            // This should be an interface, but interfaces can't inherit yet :(
                            contract IKernel is IKernelEvents, IVaultRecoverable {
                                function acl() public view returns (IACL);
                                function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                                function setApp(bytes32 namespace, bytes32 appId, address app) public;
                                function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            interface IACL {
                                function initialize(address permissionsCreator) external;
                                // TODO: this should be external
                                // See https://github.com/ethereum/solidity/issues/4832
                                function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            interface IVaultRecoverable {
                                event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
                                function transferToVault(address token) external;
                                function allowRecoverability(address token) external view returns (bool);
                                function getRecoveryVault() external view returns (address);
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            import "./Initializable.sol";
                            contract Petrifiable is Initializable {
                                // Use block UINT256_MAX (which should be never) as the initializable date
                                uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
                                function isPetrified() public view returns (bool) {
                                    return getInitializationBlock() == PETRIFIED_BLOCK;
                                }
                                /**
                                * @dev Function to be called by top level contract to prevent being initialized.
                                *      Useful for freezing base contracts when they're used behind proxies.
                                */
                                function petrify() internal onlyInit {
                                    initializedAt(PETRIFIED_BLOCK);
                                }
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            import "./TimeHelpers.sol";
                            import "./UnstructuredStorage.sol";
                            contract Initializable is TimeHelpers {
                                using UnstructuredStorage for bytes32;
                                // keccak256("aragonOS.initializable.initializationBlock")
                                bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
                                string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
                                string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
                                modifier onlyInit {
                                    require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
                                    _;
                                }
                                modifier isInitialized {
                                    require(hasInitialized(), ERROR_NOT_INITIALIZED);
                                    _;
                                }
                                /**
                                * @return Block number in which the contract was initialized
                                */
                                function getInitializationBlock() public view returns (uint256) {
                                    return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
                                }
                                /**
                                * @return Whether the contract has been initialized by the time of the current block
                                */
                                function hasInitialized() public view returns (bool) {
                                    uint256 initializationBlock = getInitializationBlock();
                                    return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
                                }
                                /**
                                * @dev Function to be called by top level contract after initialization has finished.
                                */
                                function initialized() internal onlyInit {
                                    INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
                                }
                                /**
                                * @dev Function to be called by top level contract after initialization to enable the contract
                                *      at a future block number rather than immediately.
                                */
                                function initializedAt(uint256 _blockNumber) internal onlyInit {
                                    INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
                                }
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            import "./Uint256Helpers.sol";
                            contract TimeHelpers {
                                using Uint256Helpers for uint256;
                                /**
                                * @dev Returns the current block number.
                                *      Using a function rather than `block.number` allows us to easily mock the block number in
                                *      tests.
                                */
                                function getBlockNumber() internal view returns (uint256) {
                                    return block.number;
                                }
                                /**
                                * @dev Returns the current block number, converted to uint64.
                                *      Using a function rather than `block.number` allows us to easily mock the block number in
                                *      tests.
                                */
                                function getBlockNumber64() internal view returns (uint64) {
                                    return getBlockNumber().toUint64();
                                }
                                /**
                                * @dev Returns the current timestamp.
                                *      Using a function rather than `block.timestamp` allows us to easily mock it in
                                *      tests.
                                */
                                function getTimestamp() internal view returns (uint256) {
                                    return block.timestamp; // solium-disable-line security/no-block-members
                                }
                                /**
                                * @dev Returns the current timestamp, converted to uint64.
                                *      Using a function rather than `block.timestamp` allows us to easily mock it in
                                *      tests.
                                */
                                function getTimestamp64() internal view returns (uint64) {
                                    return getTimestamp().toUint64();
                                }
                            }
                            pragma solidity ^0.4.24;
                            library Uint256Helpers {
                                uint256 private constant MAX_UINT64 = uint64(-1);
                                string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
                                function toUint64(uint256 a) internal pure returns (uint64) {
                                    require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
                                    return uint64(a);
                                }
                            }
                            // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
                            pragma solidity ^0.4.24;
                            /**
                             * @title ERC20 interface
                             * @dev see https://github.com/ethereum/EIPs/issues/20
                             */
                            contract ERC20 {
                                function totalSupply() public view returns (uint256);
                                function balanceOf(address _who) public view returns (uint256);
                                function allowance(address _owner, address _spender)
                                    public view returns (uint256);
                                function transfer(address _to, uint256 _value) public returns (bool);
                                function approve(address _spender, uint256 _value)
                                    public returns (bool);
                                function transferFrom(address _from, address _to, uint256 _value)
                                    public returns (bool);
                                event Transfer(
                                    address indexed from,
                                    address indexed to,
                                    uint256 value
                                );
                                event Approval(
                                    address indexed owner,
                                    address indexed spender,
                                    uint256 value
                                );
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            // aragonOS and aragon-apps rely on address(0) to denote native ETH, in
                            // contracts where both tokens and ETH are accepted
                            contract EtherTokenConstant {
                                address internal constant ETH = address(0);
                            }
                            // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
                            // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
                            pragma solidity ^0.4.24;
                            import "../lib/token/ERC20.sol";
                            library SafeERC20 {
                                // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
                                // https://github.com/ethereum/solidity/issues/3544
                                bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
                                string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
                                string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
                                function invokeAndCheckSuccess(address _addr, bytes memory _calldata)
                                    private
                                    returns (bool)
                                {
                                    bool ret;
                                    assembly {
                                        let ptr := mload(0x40)    // free memory pointer
                                        let success := call(
                                            gas,                  // forward all gas
                                            _addr,                // address
                                            0,                    // no value
                                            add(_calldata, 0x20), // calldata start
                                            mload(_calldata),     // calldata length
                                            ptr,                  // write output over free memory
                                            0x20                  // uint256 return
                                        )
                                        if gt(success, 0) {
                                            // Check number of bytes returned from last function call
                                            switch returndatasize
                                            // No bytes returned: assume success
                                            case 0 {
                                                ret := 1
                                            }
                                            // 32 bytes returned: check if non-zero
                                            case 0x20 {
                                                // Only return success if returned data was true
                                                // Already have output in ptr
                                                ret := eq(mload(ptr), 1)
                                            }
                                            // Not sure what was returned: don't mark as success
                                            default { }
                                        }
                                    }
                                    return ret;
                                }
                                function staticInvoke(address _addr, bytes memory _calldata)
                                    private
                                    view
                                    returns (bool, uint256)
                                {
                                    bool success;
                                    uint256 ret;
                                    assembly {
                                        let ptr := mload(0x40)    // free memory pointer
                                        success := staticcall(
                                            gas,                  // forward all gas
                                            _addr,                // address
                                            add(_calldata, 0x20), // calldata start
                                            mload(_calldata),     // calldata length
                                            ptr,                  // write output over free memory
                                            0x20                  // uint256 return
                                        )
                                        if gt(success, 0) {
                                            ret := mload(ptr)
                                        }
                                    }
                                    return (success, ret);
                                }
                                /**
                                * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
                                *      Note that this makes an external call to the token.
                                */
                                function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
                                    bytes memory transferCallData = abi.encodeWithSelector(
                                        TRANSFER_SELECTOR,
                                        _to,
                                        _amount
                                    );
                                    return invokeAndCheckSuccess(_token, transferCallData);
                                }
                                /**
                                * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
                                *      Note that this makes an external call to the token.
                                */
                                function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
                                    bytes memory transferFromCallData = abi.encodeWithSelector(
                                        _token.transferFrom.selector,
                                        _from,
                                        _to,
                                        _amount
                                    );
                                    return invokeAndCheckSuccess(_token, transferFromCallData);
                                }
                                /**
                                * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
                                *      Note that this makes an external call to the token.
                                */
                                function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
                                    bytes memory approveCallData = abi.encodeWithSelector(
                                        _token.approve.selector,
                                        _spender,
                                        _amount
                                    );
                                    return invokeAndCheckSuccess(_token, approveCallData);
                                }
                                /**
                                * @dev Static call into ERC20.balanceOf().
                                * Reverts if the call fails for some reason (should never fail).
                                */
                                function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
                                    bytes memory balanceOfCallData = abi.encodeWithSelector(
                                        _token.balanceOf.selector,
                                        _owner
                                    );
                                    (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
                                    require(success, ERROR_TOKEN_BALANCE_REVERTED);
                                    return tokenBalance;
                                }
                                /**
                                * @dev Static call into ERC20.allowance().
                                * Reverts if the call fails for some reason (should never fail).
                                */
                                function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
                                    bytes memory allowanceCallData = abi.encodeWithSelector(
                                        _token.allowance.selector,
                                        _owner,
                                        _spender
                                    );
                                    (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
                                    require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
                                    return allowance;
                                }
                                /**
                                * @dev Static call into ERC20.totalSupply().
                                * Reverts if the call fails for some reason (should never fail).
                                */
                                function staticTotalSupply(ERC20 _token) internal view returns (uint256) {
                                    bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector);
                                    (bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData);
                                    require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
                                    return totalSupply;
                                }
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            interface IEVMScriptExecutor {
                                function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes);
                                function executorType() external pure returns (bytes32);
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            import "./IEVMScriptExecutor.sol";
                            contract EVMScriptRegistryConstants {
                                /* Hardcoded constants to save gas
                                bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg");
                                */
                                bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61;
                            }
                            interface IEVMScriptRegistry {
                                function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id);
                                function disableScriptExecutor(uint256 executorId) external;
                                // TODO: this should be external
                                // See https://github.com/ethereum/solidity/issues/4832
                                function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor);
                            }
                            /*
                             * SPDX-License-Identifier:    MIT
                             */
                            pragma solidity ^0.4.24;
                            contract KernelAppIds {
                                /* Hardcoded constants to save gas
                                bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
                                bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
                                bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
                                */
                                bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
                                bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
                                bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
                            }
                            contract KernelNamespaceConstants {
                                /* Hardcoded constants to save gas
                                bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
                                bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
                                bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
                                */
                                bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
                                bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
                                bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
                            }
                            pragma solidity ^0.4.24;
                            /**
                             * @title ERC20 interface
                             * @dev see https://github.com/ethereum/EIPs/issues/20
                             */
                            interface IERC20 {
                              function totalSupply() external view returns (uint256);
                              function balanceOf(address who) external view returns (uint256);
                              function allowance(address owner, address spender)
                                external view returns (uint256);
                              function transfer(address to, uint256 value) external returns (bool);
                              function approve(address spender, uint256 value)
                                external returns (bool);
                              function transferFrom(address from, address to, uint256 value)
                                external returns (bool);
                              event Transfer(
                                address indexed from,
                                address indexed to,
                                uint256 value
                              );
                              event Approval(
                                address indexed owner,
                                address indexed spender,
                                uint256 value
                              );
                            }
                            // SPDX-FileCopyrightText: 2020 Lido <[email protected]>
                            // SPDX-License-Identifier: GPL-3.0
                            pragma solidity 0.4.24;
                            import "@aragon/os/contracts/common/UnstructuredStorage.sol";
                            contract Pausable {
                                using UnstructuredStorage for bytes32;
                                event Stopped();
                                event Resumed();
                                bytes32 internal constant ACTIVE_FLAG_POSITION = keccak256("lido.Pausable.activeFlag");
                                modifier whenNotStopped() {
                                    require(ACTIVE_FLAG_POSITION.getStorageBool(), "CONTRACT_IS_STOPPED");
                                    _;
                                }
                                modifier whenStopped() {
                                    require(!ACTIVE_FLAG_POSITION.getStorageBool(), "CONTRACT_IS_ACTIVE");
                                    _;
                                }
                                function isStopped() external view returns (bool) {
                                    return !ACTIVE_FLAG_POSITION.getStorageBool();
                                }
                                function _stop() internal whenNotStopped {
                                    ACTIVE_FLAG_POSITION.setStorageBool(false);
                                    emit Stopped();
                                }
                                function _resume() internal whenStopped {
                                    ACTIVE_FLAG_POSITION.setStorageBool(true);
                                    emit Resumed();
                                }
                            }
                            

                            File 12 of 12: GnosisSafe
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            import "./base/ModuleManager.sol";
                            import "./base/OwnerManager.sol";
                            import "./base/FallbackManager.sol";
                            import "./base/GuardManager.sol";
                            import "./common/EtherPaymentFallback.sol";
                            import "./common/Singleton.sol";
                            import "./common/SignatureDecoder.sol";
                            import "./common/SecuredTokenTransfer.sol";
                            import "./common/StorageAccessible.sol";
                            import "./interfaces/ISignatureValidator.sol";
                            import "./external/GnosisSafeMath.sol";
                            /// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191.
                            /// @author Stefan George - <[email protected]>
                            /// @author Richard Meissner - <[email protected]>
                            contract GnosisSafe is
                                EtherPaymentFallback,
                                Singleton,
                                ModuleManager,
                                OwnerManager,
                                SignatureDecoder,
                                SecuredTokenTransfer,
                                ISignatureValidatorConstants,
                                FallbackManager,
                                StorageAccessible,
                                GuardManager
                            {
                                using GnosisSafeMath for uint256;
                                string public constant VERSION = "1.3.0";
                                // keccak256(
                                //     "EIP712Domain(uint256 chainId,address verifyingContract)"
                                // );
                                bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;
                                // keccak256(
                                //     "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)"
                                // );
                                bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8;
                                event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler);
                                event ApproveHash(bytes32 indexed approvedHash, address indexed owner);
                                event SignMsg(bytes32 indexed msgHash);
                                event ExecutionFailure(bytes32 txHash, uint256 payment);
                                event ExecutionSuccess(bytes32 txHash, uint256 payment);
                                uint256 public nonce;
                                bytes32 private _deprecatedDomainSeparator;
                                // Mapping to keep track of all message hashes that have been approve by ALL REQUIRED owners
                                mapping(bytes32 => uint256) public signedMessages;
                                // Mapping to keep track of all hashes (message or transaction) that have been approve by ANY owners
                                mapping(address => mapping(bytes32 => uint256)) public approvedHashes;
                                // This constructor ensures that this contract can only be used as a master copy for Proxy contracts
                                constructor() {
                                    // By setting the threshold it is not possible to call setup anymore,
                                    // so we create a Safe with 0 owners and threshold 1.
                                    // This is an unusable Safe, perfect for the singleton
                                    threshold = 1;
                                }
                                /// @dev Setup function sets initial storage of contract.
                                /// @param _owners List of Safe owners.
                                /// @param _threshold Number of required confirmations for a Safe transaction.
                                /// @param to Contract address for optional delegate call.
                                /// @param data Data payload for optional delegate call.
                                /// @param fallbackHandler Handler for fallback calls to this contract
                                /// @param paymentToken Token that should be used for the payment (0 is ETH)
                                /// @param payment Value that should be paid
                                /// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin)
                                function setup(
                                    address[] calldata _owners,
                                    uint256 _threshold,
                                    address to,
                                    bytes calldata data,
                                    address fallbackHandler,
                                    address paymentToken,
                                    uint256 payment,
                                    address payable paymentReceiver
                                ) external {
                                    // setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice
                                    setupOwners(_owners, _threshold);
                                    if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);
                                    // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules
                                    setupModules(to, data);
                                    if (payment > 0) {
                                        // To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself)
                                        // baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment
                                        handlePayment(payment, 0, 1, paymentToken, paymentReceiver);
                                    }
                                    emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler);
                                }
                                /// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction.
                                ///      Note: The fees are always transferred, even if the user transaction fails.
                                /// @param to Destination address of Safe transaction.
                                /// @param value Ether value of Safe transaction.
                                /// @param data Data payload of Safe transaction.
                                /// @param operation Operation type of Safe transaction.
                                /// @param safeTxGas Gas that should be used for the Safe transaction.
                                /// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
                                /// @param gasPrice Gas price that should be used for the payment calculation.
                                /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
                                /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
                                /// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v})
                                function execTransaction(
                                    address to,
                                    uint256 value,
                                    bytes calldata data,
                                    Enum.Operation operation,
                                    uint256 safeTxGas,
                                    uint256 baseGas,
                                    uint256 gasPrice,
                                    address gasToken,
                                    address payable refundReceiver,
                                    bytes memory signatures
                                ) public payable virtual returns (bool success) {
                                    bytes32 txHash;
                                    // Use scope here to limit variable lifetime and prevent `stack too deep` errors
                                    {
                                        bytes memory txHashData =
                                            encodeTransactionData(
                                                // Transaction info
                                                to,
                                                value,
                                                data,
                                                operation,
                                                safeTxGas,
                                                // Payment info
                                                baseGas,
                                                gasPrice,
                                                gasToken,
                                                refundReceiver,
                                                // Signature info
                                                nonce
                                            );
                                        // Increase nonce and execute transaction.
                                        nonce++;
                                        txHash = keccak256(txHashData);
                                        checkSignatures(txHash, txHashData, signatures);
                                    }
                                    address guard = getGuard();
                                    {
                                        if (guard != address(0)) {
                                            Guard(guard).checkTransaction(
                                                // Transaction info
                                                to,
                                                value,
                                                data,
                                                operation,
                                                safeTxGas,
                                                // Payment info
                                                baseGas,
                                                gasPrice,
                                                gasToken,
                                                refundReceiver,
                                                // Signature info
                                                signatures,
                                                msg.sender
                                            );
                                        }
                                    }
                                    // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500)
                                    // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150
                                    require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010");
                                    // Use scope here to limit variable lifetime and prevent `stack too deep` errors
                                    {
                                        uint256 gasUsed = gasleft();
                                        // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas)
                                        // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas
                                        success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas);
                                        gasUsed = gasUsed.sub(gasleft());
                                        // If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful
                                        // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert
                                        require(success || safeTxGas != 0 || gasPrice != 0, "GS013");
                                        // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls
                                        uint256 payment = 0;
                                        if (gasPrice > 0) {
                                            payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver);
                                        }
                                        if (success) emit ExecutionSuccess(txHash, payment);
                                        else emit ExecutionFailure(txHash, payment);
                                    }
                                    {
                                        if (guard != address(0)) {
                                            Guard(guard).checkAfterExecution(txHash, success);
                                        }
                                    }
                                }
                                function handlePayment(
                                    uint256 gasUsed,
                                    uint256 baseGas,
                                    uint256 gasPrice,
                                    address gasToken,
                                    address payable refundReceiver
                                ) private returns (uint256 payment) {
                                    // solhint-disable-next-line avoid-tx-origin
                                    address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver;
                                    if (gasToken == address(0)) {
                                        // For ETH we will only adjust the gas price to not be higher than the actual used gas price
                                        payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice);
                                        require(receiver.send(payment), "GS011");
                                    } else {
                                        payment = gasUsed.add(baseGas).mul(gasPrice);
                                        require(transferToken(gasToken, receiver, payment), "GS012");
                                    }
                                }
                                /**
                                 * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
                                 * @param dataHash Hash of the data (could be either a message hash or transaction hash)
                                 * @param data That should be signed (this is passed to an external validator contract)
                                 * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
                                 */
                                function checkSignatures(
                                    bytes32 dataHash,
                                    bytes memory data,
                                    bytes memory signatures
                                ) public view {
                                    // Load threshold to avoid multiple storage loads
                                    uint256 _threshold = threshold;
                                    // Check that a threshold is set
                                    require(_threshold > 0, "GS001");
                                    checkNSignatures(dataHash, data, signatures, _threshold);
                                }
                                /**
                                 * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
                                 * @param dataHash Hash of the data (could be either a message hash or transaction hash)
                                 * @param data That should be signed (this is passed to an external validator contract)
                                 * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
                                 * @param requiredSignatures Amount of required valid signatures.
                                 */
                                function checkNSignatures(
                                    bytes32 dataHash,
                                    bytes memory data,
                                    bytes memory signatures,
                                    uint256 requiredSignatures
                                ) public view {
                                    // Check that the provided signature data is not too short
                                    require(signatures.length >= requiredSignatures.mul(65), "GS020");
                                    // There cannot be an owner with address 0.
                                    address lastOwner = address(0);
                                    address currentOwner;
                                    uint8 v;
                                    bytes32 r;
                                    bytes32 s;
                                    uint256 i;
                                    for (i = 0; i < requiredSignatures; i++) {
                                        (v, r, s) = signatureSplit(signatures, i);
                                        if (v == 0) {
                                            // If v is 0 then it is a contract signature
                                            // When handling contract signatures the address of the contract is encoded into r
                                            currentOwner = address(uint160(uint256(r)));
                                            // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes
                                            // This check is not completely accurate, since it is possible that more signatures than the threshold are send.
                                            // Here we only check that the pointer is not pointing inside the part that is being processed
                                            require(uint256(s) >= requiredSignatures.mul(65), "GS021");
                                            // Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes)
                                            require(uint256(s).add(32) <= signatures.length, "GS022");
                                            // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length
                                            uint256 contractSignatureLen;
                                            // solhint-disable-next-line no-inline-assembly
                                            assembly {
                                                contractSignatureLen := mload(add(add(signatures, s), 0x20))
                                            }
                                            require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023");
                                            // Check signature
                                            bytes memory contractSignature;
                                            // solhint-disable-next-line no-inline-assembly
                                            assembly {
                                                // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s
                                                contractSignature := add(add(signatures, s), 0x20)
                                            }
                                            require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "GS024");
                                        } else if (v == 1) {
                                            // If v is 1 then it is an approved hash
                                            // When handling approved hashes the address of the approver is encoded into r
                                            currentOwner = address(uint160(uint256(r)));
                                            // Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction
                                            require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "GS025");
                                        } else if (v > 30) {
                                            // If v > 30 then default va (27,28) has been adjusted for eth_sign flow
                                            // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover
                                            currentOwner = ecrecover(keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
                            32", dataHash)), v - 4, r, s);
                                        } else {
                                            // Default is the ecrecover flow with the provided data hash
                                            // Use ecrecover with the messageHash for EOA signatures
                                            currentOwner = ecrecover(dataHash, v, r, s);
                                        }
                                        require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "GS026");
                                        lastOwner = currentOwner;
                                    }
                                }
                                /// @dev Allows to estimate a Safe transaction.
                                ///      This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.
                                ///      Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction`
                                /// @param to Destination address of Safe transaction.
                                /// @param value Ether value of Safe transaction.
                                /// @param data Data payload of Safe transaction.
                                /// @param operation Operation type of Safe transaction.
                                /// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).
                                /// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version.
                                function requiredTxGas(
                                    address to,
                                    uint256 value,
                                    bytes calldata data,
                                    Enum.Operation operation
                                ) external returns (uint256) {
                                    uint256 startGas = gasleft();
                                    // We don't provide an error message here, as we use it to return the estimate
                                    require(execute(to, value, data, operation, gasleft()));
                                    uint256 requiredGas = startGas - gasleft();
                                    // Convert response to string and return via error message
                                    revert(string(abi.encodePacked(requiredGas)));
                                }
                                /**
                                 * @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature.
                                 * @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract.
                                 */
                                function approveHash(bytes32 hashToApprove) external {
                                    require(owners[msg.sender] != address(0), "GS030");
                                    approvedHashes[msg.sender][hashToApprove] = 1;
                                    emit ApproveHash(hashToApprove, msg.sender);
                                }
                                /// @dev Returns the chain id used by this contract.
                                function getChainId() public view returns (uint256) {
                                    uint256 id;
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        id := chainid()
                                    }
                                    return id;
                                }
                                function domainSeparator() public view returns (bytes32) {
                                    return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this));
                                }
                                /// @dev Returns the bytes that are hashed to be signed by owners.
                                /// @param to Destination address.
                                /// @param value Ether value.
                                /// @param data Data payload.
                                /// @param operation Operation type.
                                /// @param safeTxGas Gas that should be used for the safe transaction.
                                /// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
                                /// @param gasPrice Maximum gas price that should be used for this transaction.
                                /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
                                /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
                                /// @param _nonce Transaction nonce.
                                /// @return Transaction hash bytes.
                                function encodeTransactionData(
                                    address to,
                                    uint256 value,
                                    bytes calldata data,
                                    Enum.Operation operation,
                                    uint256 safeTxGas,
                                    uint256 baseGas,
                                    uint256 gasPrice,
                                    address gasToken,
                                    address refundReceiver,
                                    uint256 _nonce
                                ) public view returns (bytes memory) {
                                    bytes32 safeTxHash =
                                        keccak256(
                                            abi.encode(
                                                SAFE_TX_TYPEHASH,
                                                to,
                                                value,
                                                keccak256(data),
                                                operation,
                                                safeTxGas,
                                                baseGas,
                                                gasPrice,
                                                gasToken,
                                                refundReceiver,
                                                _nonce
                                            )
                                        );
                                    return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash);
                                }
                                /// @dev Returns hash to be signed by owners.
                                /// @param to Destination address.
                                /// @param value Ether value.
                                /// @param data Data payload.
                                /// @param operation Operation type.
                                /// @param safeTxGas Fas that should be used for the safe transaction.
                                /// @param baseGas Gas costs for data used to trigger the safe transaction.
                                /// @param gasPrice Maximum gas price that should be used for this transaction.
                                /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
                                /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
                                /// @param _nonce Transaction nonce.
                                /// @return Transaction hash.
                                function getTransactionHash(
                                    address to,
                                    uint256 value,
                                    bytes calldata data,
                                    Enum.Operation operation,
                                    uint256 safeTxGas,
                                    uint256 baseGas,
                                    uint256 gasPrice,
                                    address gasToken,
                                    address refundReceiver,
                                    uint256 _nonce
                                ) public view returns (bytes32) {
                                    return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce));
                                }
                            }
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            import "../common/Enum.sol";
                            /// @title Executor - A contract that can execute transactions
                            /// @author Richard Meissner - <[email protected]>
                            contract Executor {
                                function execute(
                                    address to,
                                    uint256 value,
                                    bytes memory data,
                                    Enum.Operation operation,
                                    uint256 txGas
                                ) internal returns (bool success) {
                                    if (operation == Enum.Operation.DelegateCall) {
                                        // solhint-disable-next-line no-inline-assembly
                                        assembly {
                                            success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0)
                                        }
                                    } else {
                                        // solhint-disable-next-line no-inline-assembly
                                        assembly {
                                            success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0)
                                        }
                                    }
                                }
                            }
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            import "../common/SelfAuthorized.sol";
                            /// @title Fallback Manager - A contract that manages fallback calls made to this contract
                            /// @author Richard Meissner - <[email protected]>
                            contract FallbackManager is SelfAuthorized {
                                event ChangedFallbackHandler(address handler);
                                // keccak256("fallback_manager.handler.address")
                                bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;
                                function internalSetFallbackHandler(address handler) internal {
                                    bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        sstore(slot, handler)
                                    }
                                }
                                /// @dev Allows to add a contract to handle fallback calls.
                                ///      Only fallback calls without value and with data will be forwarded.
                                ///      This can only be done via a Safe transaction.
                                /// @param handler contract to handle fallbacks calls.
                                function setFallbackHandler(address handler) public authorized {
                                    internalSetFallbackHandler(handler);
                                    emit ChangedFallbackHandler(handler);
                                }
                                // solhint-disable-next-line payable-fallback,no-complex-fallback
                                fallback() external {
                                    bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        let handler := sload(slot)
                                        if iszero(handler) {
                                            return(0, 0)
                                        }
                                        calldatacopy(0, 0, calldatasize())
                                        // The msg.sender address is shifted to the left by 12 bytes to remove the padding
                                        // Then the address without padding is stored right after the calldata
                                        mstore(calldatasize(), shl(96, caller()))
                                        // Add 20 bytes for the address appended add the end
                                        let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0)
                                        returndatacopy(0, 0, returndatasize())
                                        if iszero(success) {
                                            revert(0, returndatasize())
                                        }
                                        return(0, returndatasize())
                                    }
                                }
                            }
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            import "../common/Enum.sol";
                            import "../common/SelfAuthorized.sol";
                            interface Guard {
                                function checkTransaction(
                                    address to,
                                    uint256 value,
                                    bytes memory data,
                                    Enum.Operation operation,
                                    uint256 safeTxGas,
                                    uint256 baseGas,
                                    uint256 gasPrice,
                                    address gasToken,
                                    address payable refundReceiver,
                                    bytes memory signatures,
                                    address msgSender
                                ) external;
                                function checkAfterExecution(bytes32 txHash, bool success) external;
                            }
                            /// @title Fallback Manager - A contract that manages fallback calls made to this contract
                            /// @author Richard Meissner - <[email protected]>
                            contract GuardManager is SelfAuthorized {
                                event ChangedGuard(address guard);
                                // keccak256("guard_manager.guard.address")
                                bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
                                /// @dev Set a guard that checks transactions before execution
                                /// @param guard The address of the guard to be used or the 0 address to disable the guard
                                function setGuard(address guard) external authorized {
                                    bytes32 slot = GUARD_STORAGE_SLOT;
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        sstore(slot, guard)
                                    }
                                    emit ChangedGuard(guard);
                                }
                                function getGuard() internal view returns (address guard) {
                                    bytes32 slot = GUARD_STORAGE_SLOT;
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        guard := sload(slot)
                                    }
                                }
                            }
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            import "../common/Enum.sol";
                            import "../common/SelfAuthorized.sol";
                            import "./Executor.sol";
                            /// @title Module Manager - A contract that manages modules that can execute transactions via this contract
                            /// @author Stefan George - <[email protected]>
                            /// @author Richard Meissner - <[email protected]>
                            contract ModuleManager is SelfAuthorized, Executor {
                                event EnabledModule(address module);
                                event DisabledModule(address module);
                                event ExecutionFromModuleSuccess(address indexed module);
                                event ExecutionFromModuleFailure(address indexed module);
                                address internal constant SENTINEL_MODULES = address(0x1);
                                mapping(address => address) internal modules;
                                function setupModules(address to, bytes memory data) internal {
                                    require(modules[SENTINEL_MODULES] == address(0), "GS100");
                                    modules[SENTINEL_MODULES] = SENTINEL_MODULES;
                                    if (to != address(0))
                                        // Setup has to complete successfully or transaction fails.
                                        require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000");
                                }
                                /// @dev Allows to add a module to the whitelist.
                                ///      This can only be done via a Safe transaction.
                                /// @notice Enables the module `module` for the Safe.
                                /// @param module Module to be whitelisted.
                                function enableModule(address module) public authorized {
                                    // Module address cannot be null or sentinel.
                                    require(module != address(0) && module != SENTINEL_MODULES, "GS101");
                                    // Module cannot be added twice.
                                    require(modules[module] == address(0), "GS102");
                                    modules[module] = modules[SENTINEL_MODULES];
                                    modules[SENTINEL_MODULES] = module;
                                    emit EnabledModule(module);
                                }
                                /// @dev Allows to remove a module from the whitelist.
                                ///      This can only be done via a Safe transaction.
                                /// @notice Disables the module `module` for the Safe.
                                /// @param prevModule Module that pointed to the module to be removed in the linked list
                                /// @param module Module to be removed.
                                function disableModule(address prevModule, address module) public authorized {
                                    // Validate module address and check that it corresponds to module index.
                                    require(module != address(0) && module != SENTINEL_MODULES, "GS101");
                                    require(modules[prevModule] == module, "GS103");
                                    modules[prevModule] = modules[module];
                                    modules[module] = address(0);
                                    emit DisabledModule(module);
                                }
                                /// @dev Allows a Module to execute a Safe transaction without any further confirmations.
                                /// @param to Destination address of module transaction.
                                /// @param value Ether value of module transaction.
                                /// @param data Data payload of module transaction.
                                /// @param operation Operation type of module transaction.
                                function execTransactionFromModule(
                                    address to,
                                    uint256 value,
                                    bytes memory data,
                                    Enum.Operation operation
                                ) public virtual returns (bool success) {
                                    // Only whitelisted modules are allowed.
                                    require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "GS104");
                                    // Execute transaction without further confirmations.
                                    success = execute(to, value, data, operation, gasleft());
                                    if (success) emit ExecutionFromModuleSuccess(msg.sender);
                                    else emit ExecutionFromModuleFailure(msg.sender);
                                }
                                /// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data
                                /// @param to Destination address of module transaction.
                                /// @param value Ether value of module transaction.
                                /// @param data Data payload of module transaction.
                                /// @param operation Operation type of module transaction.
                                function execTransactionFromModuleReturnData(
                                    address to,
                                    uint256 value,
                                    bytes memory data,
                                    Enum.Operation operation
                                ) public returns (bool success, bytes memory returnData) {
                                    success = execTransactionFromModule(to, value, data, operation);
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        // Load free memory location
                                        let ptr := mload(0x40)
                                        // We allocate memory for the return data by setting the free memory location to
                                        // current free memory location + data size + 32 bytes for data size value
                                        mstore(0x40, add(ptr, add(returndatasize(), 0x20)))
                                        // Store the size
                                        mstore(ptr, returndatasize())
                                        // Store the data
                                        returndatacopy(add(ptr, 0x20), 0, returndatasize())
                                        // Point the return data to the correct memory location
                                        returnData := ptr
                                    }
                                }
                                /// @dev Returns if an module is enabled
                                /// @return True if the module is enabled
                                function isModuleEnabled(address module) public view returns (bool) {
                                    return SENTINEL_MODULES != module && modules[module] != address(0);
                                }
                                /// @dev Returns array of modules.
                                /// @param start Start of the page.
                                /// @param pageSize Maximum number of modules that should be returned.
                                /// @return array Array of modules.
                                /// @return next Start of the next page.
                                function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) {
                                    // Init array with max page size
                                    array = new address[](pageSize);
                                    // Populate return array
                                    uint256 moduleCount = 0;
                                    address currentModule = modules[start];
                                    while (currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) {
                                        array[moduleCount] = currentModule;
                                        currentModule = modules[currentModule];
                                        moduleCount++;
                                    }
                                    next = currentModule;
                                    // Set correct size of returned array
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        mstore(array, moduleCount)
                                    }
                                }
                            }
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            import "../common/SelfAuthorized.sol";
                            /// @title OwnerManager - Manages a set of owners and a threshold to perform actions.
                            /// @author Stefan George - <[email protected]>
                            /// @author Richard Meissner - <[email protected]>
                            contract OwnerManager is SelfAuthorized {
                                event AddedOwner(address owner);
                                event RemovedOwner(address owner);
                                event ChangedThreshold(uint256 threshold);
                                address internal constant SENTINEL_OWNERS = address(0x1);
                                mapping(address => address) internal owners;
                                uint256 internal ownerCount;
                                uint256 internal threshold;
                                /// @dev Setup function sets initial storage of contract.
                                /// @param _owners List of Safe owners.
                                /// @param _threshold Number of required confirmations for a Safe transaction.
                                function setupOwners(address[] memory _owners, uint256 _threshold) internal {
                                    // Threshold can only be 0 at initialization.
                                    // Check ensures that setup function can only be called once.
                                    require(threshold == 0, "GS200");
                                    // Validate that threshold is smaller than number of added owners.
                                    require(_threshold <= _owners.length, "GS201");
                                    // There has to be at least one Safe owner.
                                    require(_threshold >= 1, "GS202");
                                    // Initializing Safe owners.
                                    address currentOwner = SENTINEL_OWNERS;
                                    for (uint256 i = 0; i < _owners.length; i++) {
                                        // Owner address cannot be null.
                                        address owner = _owners[i];
                                        require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, "GS203");
                                        // No duplicate owners allowed.
                                        require(owners[owner] == address(0), "GS204");
                                        owners[currentOwner] = owner;
                                        currentOwner = owner;
                                    }
                                    owners[currentOwner] = SENTINEL_OWNERS;
                                    ownerCount = _owners.length;
                                    threshold = _threshold;
                                }
                                /// @dev Allows to add a new owner to the Safe and update the threshold at the same time.
                                ///      This can only be done via a Safe transaction.
                                /// @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`.
                                /// @param owner New owner address.
                                /// @param _threshold New threshold.
                                function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized {
                                    // Owner address cannot be null, the sentinel or the Safe itself.
                                    require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), "GS203");
                                    // No duplicate owners allowed.
                                    require(owners[owner] == address(0), "GS204");
                                    owners[owner] = owners[SENTINEL_OWNERS];
                                    owners[SENTINEL_OWNERS] = owner;
                                    ownerCount++;
                                    emit AddedOwner(owner);
                                    // Change threshold if threshold was changed.
                                    if (threshold != _threshold) changeThreshold(_threshold);
                                }
                                /// @dev Allows to remove an owner from the Safe and update the threshold at the same time.
                                ///      This can only be done via a Safe transaction.
                                /// @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`.
                                /// @param prevOwner Owner that pointed to the owner to be removed in the linked list
                                /// @param owner Owner address to be removed.
                                /// @param _threshold New threshold.
                                function removeOwner(
                                    address prevOwner,
                                    address owner,
                                    uint256 _threshold
                                ) public authorized {
                                    // Only allow to remove an owner, if threshold can still be reached.
                                    require(ownerCount - 1 >= _threshold, "GS201");
                                    // Validate owner address and check that it corresponds to owner index.
                                    require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203");
                                    require(owners[prevOwner] == owner, "GS205");
                                    owners[prevOwner] = owners[owner];
                                    owners[owner] = address(0);
                                    ownerCount--;
                                    emit RemovedOwner(owner);
                                    // Change threshold if threshold was changed.
                                    if (threshold != _threshold) changeThreshold(_threshold);
                                }
                                /// @dev Allows to swap/replace an owner from the Safe with another address.
                                ///      This can only be done via a Safe transaction.
                                /// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`.
                                /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list
                                /// @param oldOwner Owner address to be replaced.
                                /// @param newOwner New owner address.
                                function swapOwner(
                                    address prevOwner,
                                    address oldOwner,
                                    address newOwner
                                ) public authorized {
                                    // Owner address cannot be null, the sentinel or the Safe itself.
                                    require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203");
                                    // No duplicate owners allowed.
                                    require(owners[newOwner] == address(0), "GS204");
                                    // Validate oldOwner address and check that it corresponds to owner index.
                                    require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203");
                                    require(owners[prevOwner] == oldOwner, "GS205");
                                    owners[newOwner] = owners[oldOwner];
                                    owners[prevOwner] = newOwner;
                                    owners[oldOwner] = address(0);
                                    emit RemovedOwner(oldOwner);
                                    emit AddedOwner(newOwner);
                                }
                                /// @dev Allows to update the number of required confirmations by Safe owners.
                                ///      This can only be done via a Safe transaction.
                                /// @notice Changes the threshold of the Safe to `_threshold`.
                                /// @param _threshold New threshold.
                                function changeThreshold(uint256 _threshold) public authorized {
                                    // Validate that threshold is smaller than number of owners.
                                    require(_threshold <= ownerCount, "GS201");
                                    // There has to be at least one Safe owner.
                                    require(_threshold >= 1, "GS202");
                                    threshold = _threshold;
                                    emit ChangedThreshold(threshold);
                                }
                                function getThreshold() public view returns (uint256) {
                                    return threshold;
                                }
                                function isOwner(address owner) public view returns (bool) {
                                    return owner != SENTINEL_OWNERS && owners[owner] != address(0);
                                }
                                /// @dev Returns array of owners.
                                /// @return Array of Safe owners.
                                function getOwners() public view returns (address[] memory) {
                                    address[] memory array = new address[](ownerCount);
                                    // populate return array
                                    uint256 index = 0;
                                    address currentOwner = owners[SENTINEL_OWNERS];
                                    while (currentOwner != SENTINEL_OWNERS) {
                                        array[index] = currentOwner;
                                        currentOwner = owners[currentOwner];
                                        index++;
                                    }
                                    return array;
                                }
                            }
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            /// @title Enum - Collection of enums
                            /// @author Richard Meissner - <[email protected]>
                            contract Enum {
                                enum Operation {Call, DelegateCall}
                            }
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            /// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments
                            /// @author Richard Meissner - <[email protected]>
                            contract EtherPaymentFallback {
                                event SafeReceived(address indexed sender, uint256 value);
                                /// @dev Fallback function accepts Ether transactions.
                                receive() external payable {
                                    emit SafeReceived(msg.sender, msg.value);
                                }
                            }
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            /// @title SecuredTokenTransfer - Secure token transfer
                            /// @author Richard Meissner - <[email protected]>
                            contract SecuredTokenTransfer {
                                /// @dev Transfers a token and returns if it was a success
                                /// @param token Token that should be transferred
                                /// @param receiver Receiver to whom the token should be transferred
                                /// @param amount The amount of tokens that should be transferred
                                function transferToken(
                                    address token,
                                    address receiver,
                                    uint256 amount
                                ) internal returns (bool transferred) {
                                    // 0xa9059cbb - keccack("transfer(address,uint256)")
                                    bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount);
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        // We write the return value to scratch space.
                                        // See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory
                                        let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20)
                                        switch returndatasize()
                                            case 0 {
                                                transferred := success
                                            }
                                            case 0x20 {
                                                transferred := iszero(or(iszero(success), iszero(mload(0))))
                                            }
                                            default {
                                                transferred := 0
                                            }
                                    }
                                }
                            }
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            /// @title SelfAuthorized - authorizes current contract to perform actions
                            /// @author Richard Meissner - <[email protected]>
                            contract SelfAuthorized {
                                function requireSelfCall() private view {
                                    require(msg.sender == address(this), "GS031");
                                }
                                modifier authorized() {
                                    // This is a function call as it minimized the bytecode size
                                    requireSelfCall();
                                    _;
                                }
                            }
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            /// @title SignatureDecoder - Decodes signatures that a encoded as bytes
                            /// @author Richard Meissner - <[email protected]>
                            contract SignatureDecoder {
                                /// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`.
                                /// @notice Make sure to peform a bounds check for @param pos, to avoid out of bounds access on @param signatures
                                /// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access
                                /// @param signatures concatenated rsv signatures
                                function signatureSplit(bytes memory signatures, uint256 pos)
                                    internal
                                    pure
                                    returns (
                                        uint8 v,
                                        bytes32 r,
                                        bytes32 s
                                    )
                                {
                                    // The signature format is a compact form of:
                                    //   {bytes32 r}{bytes32 s}{uint8 v}
                                    // Compact means, uint8 is not padded to 32 bytes.
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        let signaturePos := mul(0x41, pos)
                                        r := mload(add(signatures, add(signaturePos, 0x20)))
                                        s := mload(add(signatures, add(signaturePos, 0x40)))
                                        // Here we are loading the last 32 bytes, including 31 bytes
                                        // of 's'. There is no 'mload8' to do this.
                                        //
                                        // 'byte' is not working due to the Solidity parser, so lets
                                        // use the second best option, 'and'
                                        v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff)
                                    }
                                }
                            }
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            /// @title Singleton - Base for singleton contracts (should always be first super contract)
                            ///         This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`)
                            /// @author Richard Meissner - <[email protected]>
                            contract Singleton {
                                // singleton always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract.
                                // It should also always be ensured that the address is stored alone (uses a full word)
                                address private singleton;
                            }
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            /// @title StorageAccessible - generic base contract that allows callers to access all internal storage.
                            /// @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol
                            contract StorageAccessible {
                                /**
                                 * @dev Reads `length` bytes of storage in the currents contract
                                 * @param offset - the offset in the current contract's storage in words to start reading from
                                 * @param length - the number of words (32 bytes) of data to read
                                 * @return the bytes that were read.
                                 */
                                function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) {
                                    bytes memory result = new bytes(length * 32);
                                    for (uint256 index = 0; index < length; index++) {
                                        // solhint-disable-next-line no-inline-assembly
                                        assembly {
                                            let word := sload(add(offset, index))
                                            mstore(add(add(result, 0x20), mul(index, 0x20)), word)
                                        }
                                    }
                                    return result;
                                }
                                /**
                                 * @dev Performs a delegetecall on a targetContract in the context of self.
                                 * Internally reverts execution to avoid side effects (making it static).
                                 *
                                 * This method reverts with data equal to `abi.encode(bool(success), bytes(response))`.
                                 * Specifically, the `returndata` after a call to this method will be:
                                 * `success:bool || response.length:uint256 || response:bytes`.
                                 *
                                 * @param targetContract Address of the contract containing the code to execute.
                                 * @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments).
                                 */
                                function simulateAndRevert(address targetContract, bytes memory calldataPayload) external {
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        let success := delegatecall(gas(), targetContract, add(calldataPayload, 0x20), mload(calldataPayload), 0, 0)
                                        mstore(0x00, success)
                                        mstore(0x20, returndatasize())
                                        returndatacopy(0x40, 0, returndatasize())
                                        revert(0, add(returndatasize(), 0x40))
                                    }
                                }
                            }
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            /**
                             * @title GnosisSafeMath
                             * @dev Math operations with safety checks that revert on error
                             * Renamed from SafeMath to GnosisSafeMath to avoid conflicts
                             * TODO: remove once open zeppelin update to solc 0.5.0
                             */
                            library GnosisSafeMath {
                                /**
                                 * @dev Multiplies two numbers, reverts on 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-solidity/pull/522
                                    if (a == 0) {
                                        return 0;
                                    }
                                    uint256 c = a * b;
                                    require(c / a == b);
                                    return c;
                                }
                                /**
                                 * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
                                 */
                                function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                    require(b <= a);
                                    uint256 c = a - b;
                                    return c;
                                }
                                /**
                                 * @dev Adds two numbers, reverts on overflow.
                                 */
                                function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                    uint256 c = a + b;
                                    require(c >= a);
                                    return c;
                                }
                                /**
                                 * @dev Returns the largest of two numbers.
                                 */
                                function max(uint256 a, uint256 b) internal pure returns (uint256) {
                                    return a >= b ? a : b;
                                }
                            }
                            // SPDX-License-Identifier: LGPL-3.0-only
                            pragma solidity >=0.7.0 <0.9.0;
                            contract ISignatureValidatorConstants {
                                // bytes4(keccak256("isValidSignature(bytes,bytes)")
                                bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b;
                            }
                            abstract contract ISignatureValidator is ISignatureValidatorConstants {
                                /**
                                 * @dev Should return whether the signature provided is valid for the provided data
                                 * @param _data Arbitrary length data signed on the behalf of address(this)
                                 * @param _signature Signature byte array associated with _data
                                 *
                                 * MUST return the bytes4 magic value 0x20c13b0b when function passes.
                                 * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
                                 * MUST allow external calls
                                 */
                                function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4);
                            }