ETH Price: $2,509.07 (-0.29%)

Transaction Decoder

Block:
16579815 at Feb-07-2023 10:15:23 PM +UTC
Transaction Fee:
0.021498445349819347 ETH $53.94
Gas Used:
562,289 Gas / 38.233800323 Gwei

Emitted Events:

129 TetherToken.Transfer( from=0xa07840F92E281fc6c0b9945a5a54076b3BAc10A5, to=0x84aD7B48f066EF3e066fD26b8Ffd15fb1d93a3Cb, value=0 )
130 TetherToken.Transfer( from=0xd4B890aB9ac3C2Ad9d40192ddd60F69c6aAC41be, to=0x060Fe8b29044216Ce36c200981A196ae1Bd77fe6, value=0 )
131 TetherToken.Transfer( from=0x48210514Dc5B1e40fAa3f395Bc4C246e1B3176D3, to=0xf89e67FecCCb7e9067501feb30A2731b74d511a9, value=0 )
132 TetherToken.Transfer( from=0x060F9aCB4aefcEDb2290d71086D4c8B6efd67Fe6, to=0x5C8FDde967dA6682aE6C87d136987b3616d7c34f, value=0 )
133 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000e4e637e3750c9086cd9b125244054cff17a4dda7, 0x000000000000000000000000e5ec3af5e8eaad4939069202c102bf6e7b12b6b1, 0000000000000000000000000000000000000000000000000000000000000000 )
134 TetherToken.Transfer( from=0x96d5F564D347496f3217c2649599Bef3a1AD59Bc, to=0x96Dd3ccB83462b835d314474F9a5C1f6bd3359Bc, value=0 )
135 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x00000000000000000000000076e6161f1fd846100140cbc111d0673b216a74c6, 0x00000000000000000000000076599e69af3cf4f3c4bce722690c0db4e4ebae13, 0000000000000000000000000000000000000000000000000000000000000000 )
136 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x00000000000000000000000029d639a1ecb288b616b189298cc6699cba119f14, 0x0000000000000000000000001e5022fdd2fdfd3ee4c7117d759499ee8d591b7d, 0000000000000000000000000000000000000000000000000000000000000000 )
137 TetherToken.Transfer( from=0xF4012fFA245c7BEc5Ba5f3a5A9d02bf6a2205fc0, to=0x1ba926dac6b54739dfe2899fa0a1Edc9f1d3f3DA, value=0 )
138 TetherToken.Transfer( from=0xf7642e06f341Ab4f8c03F192e5e2D098FCEFEF96, to=0x3aF7EBFd66E8813E8B1eEc0E0005528e8e4e46c9, value=0 )
139 TetherToken.Transfer( from=0x26352D20e6A05e04a1ecc75D4a43aE9989272621, to=0x4A799603bE8b5DF9dD98098d97aA600719AeA858, value=0 )
140 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000e6e886bc24299cb31b7f54a362b1e4fe9759ee37, 0x0000000000000000000000008984b994cf10cb7dcfff2e87ef24a05d112904ae, 0000000000000000000000000000000000000000000000000000000000000000 )
141 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000f355e29967be3679a969e97bf1c84e15ef69a31d, 0x000000000000000000000000c70164f1c261f55dc22ee3be71c78174fa4791b1, 0000000000000000000000000000000000000000000000000000000000000000 )
142 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x00000000000000000000000020c2e4d99a6c73482356582adb50ed0ff5c22574, 0x0000000000000000000000005f06a46464120e5c33b33eec4e4cb2fbd6bef5e0, 0000000000000000000000000000000000000000000000000000000000000000 )
143 TetherToken.Transfer( from=0x48fF4022C6DFBFebBbb76b0f3800880cA0aD2E53, to=0xE21d88f1046EA89f4D309e4c963e00228A71BfF9, value=0 )
144 TetherToken.Transfer( from=0x9dC5d3F4FBA71a5bE0AB5b7A20E3d98f1fDDc3d7, to=0x83a7B8D82e174E32f4a552E69A2dFd34E418b607, value=0 )
145 TetherToken.Transfer( from=0x1899Db37c5629941e159100E2Ce327aD6D7a17F1, to=0x4BB9e05E5ed0063c52A658c8609E1623FB4F2Af1, value=0 )
146 TetherToken.Transfer( from=0xb86294AFf690A222860D108464E731de75Fdd952, to=0x617fA7dA031516cA4c32B72c27aa65De1645e133, value=0 )
147 AppProxyUpgradeable.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000d476e317cc861831b4376a792892ce6ceaae7885, 0x000000000000000000000000dd638881aba3fc63d8acaa4608929a5cebabcb7e, 0000000000000000000000000000000000000000000000000000000000000000 )
148 AppProxyUpgradeable.0x9d9c909296d9c674451c0c24f02cb64981eb3b727f99865939192f880a755dcb( 0x9d9c909296d9c674451c0c24f02cb64981eb3b727f99865939192f880a755dcb, 0x000000000000000000000000d476e317cc861831b4376a792892ce6ceaae7885, 0x000000000000000000000000dd638881aba3fc63d8acaa4608929a5cebabcb7e, 0000000000000000000000000000000000000000000000000000000000000000 )
149 AppProxyUpgradeable.0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925( 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, 0x000000000000000000000000d476e317cc861831b4376a792892ce6ceaae7885, 0x000000000000000000000000605d5bfdc9bb39a5bbe165cbfd23e74d2b729d83, 0000000000000000000000000000000000000000000000000000000000000000 )
150 SimpleToken.Transfer( from=0x84a85D9553f2e2E6E658C4c239103970d9fb8CB6, to=0x8b3F8ce1A2135869Dc933aDBa05Bff68806105ea, value=0 )
151 SimpleToken.Approval( owner=0x84a85D9553f2e2E6E658C4c239103970d9fb8CB6, spender=[Receiver] 0x605d5bfdc9bb39a5bbe165cbfd23e74d2b729d83, value=0 )
152 TetherToken.Transfer( from=0xD45906b673b57580B321c582d886570a18D53982, to=0x0e31811898E6DE482159f363D3Dab14D4a17375F, value=0 )
153 TetherToken.Transfer( from=0x1FAb89DcBb6CC5b12107D83c444Fa4B664c64FE4, to=0xBa93913b5614b943ac0c2d94320FB2432f937a20, value=0 )
154 TetherToken.Transfer( from=0xd53E57Cee32d473E62b52D46a0d6C8c5CB3a3B11, to=0x7e4E2712BCcdfBeeC55a5C26B0835EBF72B4dC09, value=0 )
155 TetherToken.Transfer( from=0x5964456c99BEe03B64d688E690992830D2de84d9, to=0xd3379647DfC876E0D65483A47F4A82A50aC9dfEf, value=0 )
156 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000005384ee7790121556a1c18de52a8f629bca3a082d, 0x0000000000000000000000000ab98e8b0441427fb7b47876c43553d6faefa033, 0000000000000000000000000000000000000000000000000000000000000000 )

Account State Difference:

  Address   Before After State Difference Code
(Fee Recipient: 0x37f...972)
60.651891040810961578 Eth60.652453329810961578 Eth0.000562289
0x605D5bFd...d2B729d83
0x71524Ca9...5F60755A1
0.383826445712821757 Eth
Nonce: 237
0.36232800036300241 Eth
Nonce: 238
0.021498445349819347

Execution Trace

0x605d5bfdc9bb39a5bbe165cbfd23e74d2b729d83.d48e983d( )
  • TetherToken.transferFrom( _from=0xa07840F92E281fc6c0b9945a5a54076b3BAc10A5, _to=0x84aD7B48f066EF3e066fD26b8Ffd15fb1d93a3Cb, _value=0 )
  • TetherToken.transferFrom( _from=0xd4B890aB9ac3C2Ad9d40192ddd60F69c6aAC41be, _to=0x060Fe8b29044216Ce36c200981A196ae1Bd77fe6, _value=0 )
  • TetherToken.transferFrom( _from=0x48210514Dc5B1e40fAa3f395Bc4C246e1B3176D3, _to=0xf89e67FecCCb7e9067501feb30A2731b74d511a9, _value=0 )
  • TetherToken.transferFrom( _from=0x060F9aCB4aefcEDb2290d71086D4c8B6efd67Fe6, _to=0x5C8FDde967dA6682aE6C87d136987b3616d7c34f, _value=0 )
  • FiatTokenProxy.23b872dd( )
    • FiatTokenV2_1.transferFrom( from=0xE4E637e3750c9086CD9B125244054CfF17a4dDa7, to=0xE5eC3aF5e8eAAd4939069202c102BF6e7B12B6B1, value=0 ) => ( True )
    • TetherToken.transferFrom( _from=0x96d5F564D347496f3217c2649599Bef3a1AD59Bc, _to=0x96Dd3ccB83462b835d314474F9a5C1f6bd3359Bc, _value=0 )
    • FiatTokenProxy.23b872dd( )
      • FiatTokenV2_1.transferFrom( from=0x76e6161f1FD846100140cBc111D0673B216a74c6, to=0x76599E69af3cF4F3c4bCe722690c0Db4E4EbAe13, value=0 ) => ( True )
      • FiatTokenProxy.23b872dd( )
        • FiatTokenV2_1.transferFrom( from=0x29d639a1eCB288B616b189298cC6699cbA119f14, to=0x1E5022Fdd2FdfD3Ee4c7117d759499ee8d591b7d, value=0 ) => ( True )
        • TetherToken.transferFrom( _from=0xF4012fFA245c7BEc5Ba5f3a5A9d02bf6a2205fc0, _to=0x1ba926dac6b54739dfe2899fa0a1Edc9f1d3f3DA, _value=0 )
        • TetherToken.transferFrom( _from=0xf7642e06f341Ab4f8c03F192e5e2D098FCEFEF96, _to=0x3aF7EBFd66E8813E8B1eEc0E0005528e8e4e46c9, _value=0 )
        • TetherToken.transferFrom( _from=0x26352D20e6A05e04a1ecc75D4a43aE9989272621, _to=0x4A799603bE8b5DF9dD98098d97aA600719AeA858, _value=0 )
        • FiatTokenProxy.23b872dd( )
          • FiatTokenV2_1.transferFrom( from=0xe6e886bC24299cB31b7f54A362b1e4fe9759eE37, to=0x8984B994cf10cb7DcfFF2e87ef24A05D112904aE, value=0 ) => ( True )
          • FiatTokenProxy.23b872dd( )
            • FiatTokenV2_1.transferFrom( from=0xf355e29967bE3679A969e97BF1C84e15EF69a31d, to=0xC70164f1c261F55dc22Ee3be71c78174FA4791B1, value=0 ) => ( True )
            • FiatTokenProxy.23b872dd( )
              • FiatTokenV2_1.transferFrom( from=0x20c2e4d99a6C73482356582ADB50ED0Ff5C22574, to=0x5F06A46464120E5C33b33Eec4e4cB2fBD6BEF5E0, value=0 ) => ( True )
              • TetherToken.transferFrom( _from=0x48fF4022C6DFBFebBbb76b0f3800880cA0aD2E53, _to=0xE21d88f1046EA89f4D309e4c963e00228A71BfF9, _value=0 )
              • TetherToken.transferFrom( _from=0x9dC5d3F4FBA71a5bE0AB5b7A20E3d98f1fDDc3d7, _to=0x83a7B8D82e174E32f4a552E69A2dFd34E418b607, _value=0 )
              • TetherToken.transferFrom( _from=0x1899Db37c5629941e159100E2Ce327aD6D7a17F1, _to=0x4BB9e05E5ed0063c52A658c8609E1623FB4F2Af1, _value=0 )
              • TetherToken.transferFrom( _from=0xb86294AFf690A222860D108464E731de75Fdd952, _to=0x617fA7dA031516cA4c32B72c27aa65De1645e133, _value=0 )
              • AppProxyUpgradeable.23b872dd( )
                • KernelProxy.be00bbd8( )
                  • Kernel.getApp( _namespace=F1F3EB40F5BC1AD1344716CED8B8A0431D840B5783AEA1FD01786BC26F35AC0F, _appId=3CA7C3E38968823CCB4C78EA688DF41356F182AE1D159E4EE608D30D68CEF320 ) => ( 0x47EbaB13B806773ec2A2d16873e2dF770D130b50 )
                  • Lido.transferFrom( _sender=0xd476E317Cc861831b4376a792892cE6CeAAe7885, _recipient=0xdd638881aBa3fc63D8aCaa4608929A5CebaBCb7e, _amount=0 ) => ( True )
                  • SimpleToken.transferFrom( sender=0x84a85D9553f2e2E6E658C4c239103970d9fb8CB6, recipient=0x8b3F8ce1A2135869Dc933aDBa05Bff68806105ea, amount=0 ) => ( True )
                  • TetherToken.transferFrom( _from=0xD45906b673b57580B321c582d886570a18D53982, _to=0x0e31811898E6DE482159f363D3Dab14D4a17375F, _value=0 )
                  • TetherToken.transferFrom( _from=0x1FAb89DcBb6CC5b12107D83c444Fa4B664c64FE4, _to=0xBa93913b5614b943ac0c2d94320FB2432f937a20, _value=0 )
                  • TetherToken.transferFrom( _from=0xd53E57Cee32d473E62b52D46a0d6C8c5CB3a3B11, _to=0x7e4E2712BCcdfBeeC55a5C26B0835EBF72B4dC09, _value=0 )
                  • TetherToken.transferFrom( _from=0x5964456c99BEe03B64d688E690992830D2de84d9, _to=0xd3379647DfC876E0D65483A47F4A82A50aC9dfEf, _value=0 )
                  • FiatTokenProxy.23b872dd( )
                    • FiatTokenV2_1.transferFrom( from=0x5384ee7790121556A1c18De52A8f629bCa3A082d, to=0x0Ab98e8b0441427fB7b47876c43553d6faefA033, value=0 ) => ( True )
                      File 1 of 8: TetherToken
                      pragma solidity ^0.4.17;
                      
                      /**
                       * @title SafeMath
                       * @dev Math operations with safety checks that throw on error
                       */
                      library SafeMath {
                          function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                              if (a == 0) {
                                  return 0;
                              }
                              uint256 c = a * b;
                              assert(c / a == b);
                              return c;
                          }
                      
                          function div(uint256 a, uint256 b) internal pure returns (uint256) {
                              // assert(b > 0); // Solidity automatically throws 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;
                          }
                      
                          function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                              assert(b <= a);
                              return a - b;
                          }
                      
                          function add(uint256 a, uint256 b) internal pure returns (uint256) {
                              uint256 c = a + b;
                              assert(c >= a);
                              return c;
                          }
                      }
                      
                      /**
                       * @title Ownable
                       * @dev The Ownable contract has an owner address, and provides basic authorization control
                       * functions, this simplifies the implementation of "user permissions".
                       */
                      contract Ownable {
                          address public owner;
                      
                          /**
                            * @dev The Ownable constructor sets the original `owner` of the contract to the sender
                            * account.
                            */
                          function Ownable() public {
                              owner = msg.sender;
                          }
                      
                          /**
                            * @dev Throws if called by any account other than the owner.
                            */
                          modifier onlyOwner() {
                              require(msg.sender == owner);
                              _;
                          }
                      
                          /**
                          * @dev Allows the current owner to transfer control of the contract to a newOwner.
                          * @param newOwner The address to transfer ownership to.
                          */
                          function transferOwnership(address newOwner) public onlyOwner {
                              if (newOwner != address(0)) {
                                  owner = newOwner;
                              }
                          }
                      
                      }
                      
                      /**
                       * @title ERC20Basic
                       * @dev Simpler version of ERC20 interface
                       * @dev see https://github.com/ethereum/EIPs/issues/20
                       */
                      contract ERC20Basic {
                          uint public _totalSupply;
                          function totalSupply() public constant returns (uint);
                          function balanceOf(address who) public constant returns (uint);
                          function transfer(address to, uint value) public;
                          event Transfer(address indexed from, address indexed to, uint value);
                      }
                      
                      /**
                       * @title ERC20 interface
                       * @dev see https://github.com/ethereum/EIPs/issues/20
                       */
                      contract ERC20 is ERC20Basic {
                          function allowance(address owner, address spender) public constant returns (uint);
                          function transferFrom(address from, address to, uint value) public;
                          function approve(address spender, uint value) public;
                          event Approval(address indexed owner, address indexed spender, uint value);
                      }
                      
                      /**
                       * @title Basic token
                       * @dev Basic version of StandardToken, with no allowances.
                       */
                      contract BasicToken is Ownable, ERC20Basic {
                          using SafeMath for uint;
                      
                          mapping(address => uint) public balances;
                      
                          // additional variables for use if transaction fees ever became necessary
                          uint public basisPointsRate = 0;
                          uint public maximumFee = 0;
                      
                          /**
                          * @dev Fix for the ERC20 short address attack.
                          */
                          modifier onlyPayloadSize(uint size) {
                              require(!(msg.data.length < size + 4));
                              _;
                          }
                      
                          /**
                          * @dev transfer token for a specified address
                          * @param _to The address to transfer to.
                          * @param _value The amount to be transferred.
                          */
                          function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) {
                              uint fee = (_value.mul(basisPointsRate)).div(10000);
                              if (fee > maximumFee) {
                                  fee = maximumFee;
                              }
                              uint sendAmount = _value.sub(fee);
                              balances[msg.sender] = balances[msg.sender].sub(_value);
                              balances[_to] = balances[_to].add(sendAmount);
                              if (fee > 0) {
                                  balances[owner] = balances[owner].add(fee);
                                  Transfer(msg.sender, owner, fee);
                              }
                              Transfer(msg.sender, _to, sendAmount);
                          }
                      
                          /**
                          * @dev Gets the balance of the specified address.
                          * @param _owner The address to query the the balance of.
                          * @return An uint representing the amount owned by the passed address.
                          */
                          function balanceOf(address _owner) public constant returns (uint balance) {
                              return balances[_owner];
                          }
                      
                      }
                      
                      /**
                       * @title Standard ERC20 token
                       *
                       * @dev Implementation of the basic standard token.
                       * @dev https://github.com/ethereum/EIPs/issues/20
                       * @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
                       */
                      contract StandardToken is BasicToken, ERC20 {
                      
                          mapping (address => mapping (address => uint)) public allowed;
                      
                          uint public constant MAX_UINT = 2**256 - 1;
                      
                          /**
                          * @dev Transfer tokens from one address to another
                          * @param _from address The address which you want to send tokens from
                          * @param _to address The address which you want to transfer to
                          * @param _value uint the amount of tokens to be transferred
                          */
                          function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
                              var _allowance = allowed[_from][msg.sender];
                      
                              // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
                              // if (_value > _allowance) throw;
                      
                              uint fee = (_value.mul(basisPointsRate)).div(10000);
                              if (fee > maximumFee) {
                                  fee = maximumFee;
                              }
                              if (_allowance < MAX_UINT) {
                                  allowed[_from][msg.sender] = _allowance.sub(_value);
                              }
                              uint sendAmount = _value.sub(fee);
                              balances[_from] = balances[_from].sub(_value);
                              balances[_to] = balances[_to].add(sendAmount);
                              if (fee > 0) {
                                  balances[owner] = balances[owner].add(fee);
                                  Transfer(_from, owner, fee);
                              }
                              Transfer(_from, _to, sendAmount);
                          }
                      
                          /**
                          * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
                          * @param _spender The address which will spend the funds.
                          * @param _value The amount of tokens to be spent.
                          */
                          function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
                      
                              // To change the approve amount you first have to reduce the addresses`
                              //  allowance to zero by calling `approve(_spender, 0)` if it is not
                              //  already 0 to mitigate the race condition described here:
                              //  https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                              require(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
                      
                              allowed[msg.sender][_spender] = _value;
                              Approval(msg.sender, _spender, _value);
                          }
                      
                          /**
                          * @dev Function to check the amount of tokens than an owner allowed to a spender.
                          * @param _owner address The address which owns the funds.
                          * @param _spender address The address which will spend the funds.
                          * @return A uint specifying the amount of tokens still available for the spender.
                          */
                          function allowance(address _owner, address _spender) public constant returns (uint remaining) {
                              return allowed[_owner][_spender];
                          }
                      
                      }
                      
                      
                      /**
                       * @title Pausable
                       * @dev Base contract which allows children to implement an emergency stop mechanism.
                       */
                      contract Pausable is Ownable {
                        event Pause();
                        event Unpause();
                      
                        bool public paused = false;
                      
                      
                        /**
                         * @dev Modifier to make a function callable only when the contract is not paused.
                         */
                        modifier whenNotPaused() {
                          require(!paused);
                          _;
                        }
                      
                        /**
                         * @dev Modifier to make a function callable only when the contract is paused.
                         */
                        modifier whenPaused() {
                          require(paused);
                          _;
                        }
                      
                        /**
                         * @dev called by the owner to pause, triggers stopped state
                         */
                        function pause() onlyOwner whenNotPaused public {
                          paused = true;
                          Pause();
                        }
                      
                        /**
                         * @dev called by the owner to unpause, returns to normal state
                         */
                        function unpause() onlyOwner whenPaused public {
                          paused = false;
                          Unpause();
                        }
                      }
                      
                      contract BlackList is Ownable, BasicToken {
                      
                          /////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) ///////
                          function getBlackListStatus(address _maker) external constant returns (bool) {
                              return isBlackListed[_maker];
                          }
                      
                          function getOwner() external constant returns (address) {
                              return owner;
                          }
                      
                          mapping (address => bool) public isBlackListed;
                          
                          function addBlackList (address _evilUser) public onlyOwner {
                              isBlackListed[_evilUser] = true;
                              AddedBlackList(_evilUser);
                          }
                      
                          function removeBlackList (address _clearedUser) public onlyOwner {
                              isBlackListed[_clearedUser] = false;
                              RemovedBlackList(_clearedUser);
                          }
                      
                          function destroyBlackFunds (address _blackListedUser) public onlyOwner {
                              require(isBlackListed[_blackListedUser]);
                              uint dirtyFunds = balanceOf(_blackListedUser);
                              balances[_blackListedUser] = 0;
                              _totalSupply -= dirtyFunds;
                              DestroyedBlackFunds(_blackListedUser, dirtyFunds);
                          }
                      
                          event DestroyedBlackFunds(address _blackListedUser, uint _balance);
                      
                          event AddedBlackList(address _user);
                      
                          event RemovedBlackList(address _user);
                      
                      }
                      
                      contract UpgradedStandardToken is StandardToken{
                          // those methods are called by the legacy contract
                          // and they must ensure msg.sender to be the contract address
                          function transferByLegacy(address from, address to, uint value) public;
                          function transferFromByLegacy(address sender, address from, address spender, uint value) public;
                          function approveByLegacy(address from, address spender, uint value) public;
                      }
                      
                      contract TetherToken is Pausable, StandardToken, BlackList {
                      
                          string public name;
                          string public symbol;
                          uint public decimals;
                          address public upgradedAddress;
                          bool public deprecated;
                      
                          //  The contract can be initialized with a number of tokens
                          //  All the tokens are deposited to the owner address
                          //
                          // @param _balance Initial supply of the contract
                          // @param _name Token Name
                          // @param _symbol Token symbol
                          // @param _decimals Token decimals
                          function TetherToken(uint _initialSupply, string _name, string _symbol, uint _decimals) public {
                              _totalSupply = _initialSupply;
                              name = _name;
                              symbol = _symbol;
                              decimals = _decimals;
                              balances[owner] = _initialSupply;
                              deprecated = false;
                          }
                      
                          // Forward ERC20 methods to upgraded contract if this one is deprecated
                          function transfer(address _to, uint _value) public whenNotPaused {
                              require(!isBlackListed[msg.sender]);
                              if (deprecated) {
                                  return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
                              } else {
                                  return super.transfer(_to, _value);
                              }
                          }
                      
                          // Forward ERC20 methods to upgraded contract if this one is deprecated
                          function transferFrom(address _from, address _to, uint _value) public whenNotPaused {
                              require(!isBlackListed[_from]);
                              if (deprecated) {
                                  return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
                              } else {
                                  return super.transferFrom(_from, _to, _value);
                              }
                          }
                      
                          // Forward ERC20 methods to upgraded contract if this one is deprecated
                          function balanceOf(address who) public constant returns (uint) {
                              if (deprecated) {
                                  return UpgradedStandardToken(upgradedAddress).balanceOf(who);
                              } else {
                                  return super.balanceOf(who);
                              }
                          }
                      
                          // Forward ERC20 methods to upgraded contract if this one is deprecated
                          function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
                              if (deprecated) {
                                  return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
                              } else {
                                  return super.approve(_spender, _value);
                              }
                          }
                      
                          // Forward ERC20 methods to upgraded contract if this one is deprecated
                          function allowance(address _owner, address _spender) public constant returns (uint remaining) {
                              if (deprecated) {
                                  return StandardToken(upgradedAddress).allowance(_owner, _spender);
                              } else {
                                  return super.allowance(_owner, _spender);
                              }
                          }
                      
                          // deprecate current contract in favour of a new one
                          function deprecate(address _upgradedAddress) public onlyOwner {
                              deprecated = true;
                              upgradedAddress = _upgradedAddress;
                              Deprecate(_upgradedAddress);
                          }
                      
                          // deprecate current contract if favour of a new one
                          function totalSupply() public constant returns (uint) {
                              if (deprecated) {
                                  return StandardToken(upgradedAddress).totalSupply();
                              } else {
                                  return _totalSupply;
                              }
                          }
                      
                          // Issue a new amount of tokens
                          // these tokens are deposited into the owner address
                          //
                          // @param _amount Number of tokens to be issued
                          function issue(uint amount) public onlyOwner {
                              require(_totalSupply + amount > _totalSupply);
                              require(balances[owner] + amount > balances[owner]);
                      
                              balances[owner] += amount;
                              _totalSupply += amount;
                              Issue(amount);
                          }
                      
                          // Redeem tokens.
                          // These tokens are withdrawn from the owner address
                          // if the balance must be enough to cover the redeem
                          // or the call will fail.
                          // @param _amount Number of tokens to be issued
                          function redeem(uint amount) public onlyOwner {
                              require(_totalSupply >= amount);
                              require(balances[owner] >= amount);
                      
                              _totalSupply -= amount;
                              balances[owner] -= amount;
                              Redeem(amount);
                          }
                      
                          function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner {
                              // Ensure transparency by hardcoding limit beyond which fees can never be added
                              require(newBasisPoints < 20);
                              require(newMaxFee < 50);
                      
                              basisPointsRate = newBasisPoints;
                              maximumFee = newMaxFee.mul(10**decimals);
                      
                              Params(basisPointsRate, maximumFee);
                          }
                      
                          // Called when new token are issued
                          event Issue(uint amount);
                      
                          // Called when tokens are redeemed
                          event Redeem(uint amount);
                      
                          // Called when contract is deprecated
                          event Deprecate(address newAddress);
                      
                          // Called if contract ever adds fees
                          event Params(uint feeBasisPoints, uint maxFee);
                      }

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

                      File 3 of 8: 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 4 of 8: SimpleToken
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.10;
                      import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
                      contract SimpleToken is ERC20 {
                          constructor(
                              string memory name,
                              string memory symbol,
                              uint256 totalSupply_
                          ) ERC20(name, symbol) {
                              _mint(msg.sender, totalSupply_);
                          }
                      }
                      // SPDX-License-Identifier: MIT
                      // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
                      pragma solidity ^0.8.0;
                      /**
                       * @dev Provides information about the current execution context, including the
                       * sender of the transaction and its data. While these are generally available
                       * via msg.sender and msg.data, they should not be accessed in such a direct
                       * manner, since when dealing with meta-transactions the account sending and
                       * paying for execution may not be the actual sender (as far as an application
                       * is concerned).
                       *
                       * This contract is only required for intermediate, library-like contracts.
                       */
                      abstract contract Context {
                          function _msgSender() internal view virtual returns (address) {
                              return msg.sender;
                          }
                          function _msgData() internal view virtual returns (bytes calldata) {
                              return msg.data;
                          }
                      }
                      // SPDX-License-Identifier: MIT
                      // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
                      pragma solidity ^0.8.0;
                      import "../IERC20.sol";
                      /**
                       * @dev Interface for the optional metadata functions from the ERC20 standard.
                       *
                       * _Available since v4.1._
                       */
                      interface IERC20Metadata is IERC20 {
                          /**
                           * @dev Returns the name of the token.
                           */
                          function name() external view returns (string memory);
                          /**
                           * @dev Returns the symbol of the token.
                           */
                          function symbol() external view returns (string memory);
                          /**
                           * @dev Returns the decimals places of the token.
                           */
                          function decimals() external view returns (uint8);
                      }
                      // SPDX-License-Identifier: MIT
                      // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
                      pragma solidity ^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);
                      }
                      // SPDX-License-Identifier: MIT
                      // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
                      pragma solidity ^0.8.0;
                      import "./IERC20.sol";
                      import "./extensions/IERC20Metadata.sol";
                      import "../../utils/Context.sol";
                      /**
                       * @dev Implementation of the {IERC20} interface.
                       *
                       * This implementation is agnostic to the way tokens are created. This means
                       * that a supply mechanism has to be added in a derived contract using {_mint}.
                       * For a generic mechanism see {ERC20PresetMinterPauser}.
                       *
                       * TIP: For a detailed writeup see our guide
                       * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
                       * to implement supply mechanisms].
                       *
                       * We have followed general OpenZeppelin Contracts guidelines: functions revert
                       * instead returning `false` on failure. This behavior is nonetheless
                       * conventional and does not conflict with the expectations of ERC20
                       * applications.
                       *
                       * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
                       * This allows applications to reconstruct the allowance for all accounts just
                       * by listening to said events. Other implementations of the EIP may not emit
                       * these events, as it isn't required by the specification.
                       *
                       * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
                       * functions have been added to mitigate the well-known issues around setting
                       * allowances. See {IERC20-approve}.
                       */
                      contract ERC20 is Context, IERC20, IERC20Metadata {
                          mapping(address => uint256) private _balances;
                          mapping(address => mapping(address => uint256)) private _allowances;
                          uint256 private _totalSupply;
                          string private _name;
                          string private _symbol;
                          /**
                           * @dev Sets the values for {name} and {symbol}.
                           *
                           * The default value of {decimals} is 18. To select a different value for
                           * {decimals} you should overload it.
                           *
                           * All two of these values are immutable: they can only be set once during
                           * construction.
                           */
                          constructor(string memory name_, string memory symbol_) {
                              _name = name_;
                              _symbol = symbol_;
                          }
                          /**
                           * @dev Returns the name of the token.
                           */
                          function name() public view virtual override returns (string memory) {
                              return _name;
                          }
                          /**
                           * @dev Returns the symbol of the token, usually a shorter version of the
                           * name.
                           */
                          function symbol() public view virtual override returns (string memory) {
                              return _symbol;
                          }
                          /**
                           * @dev Returns the number of decimals used to get its user representation.
                           * For example, if `decimals` equals `2`, a balance of `505` tokens should
                           * be displayed to a user as `5.05` (`505 / 10 ** 2`).
                           *
                           * Tokens usually opt for a value of 18, imitating the relationship between
                           * Ether and Wei. This is the value {ERC20} uses, unless this function is
                           * overridden;
                           *
                           * NOTE: This information is only used for _display_ purposes: it in
                           * no way affects any of the arithmetic of the contract, including
                           * {IERC20-balanceOf} and {IERC20-transfer}.
                           */
                          function decimals() public view virtual override returns (uint8) {
                              return 18;
                          }
                          /**
                           * @dev See {IERC20-totalSupply}.
                           */
                          function totalSupply() public view virtual override returns (uint256) {
                              return _totalSupply;
                          }
                          /**
                           * @dev See {IERC20-balanceOf}.
                           */
                          function balanceOf(address account) public view virtual override returns (uint256) {
                              return _balances[account];
                          }
                          /**
                           * @dev See {IERC20-transfer}.
                           *
                           * Requirements:
                           *
                           * - `recipient` cannot be the zero address.
                           * - the caller must have a balance of at least `amount`.
                           */
                          function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
                              _transfer(_msgSender(), recipient, amount);
                              return true;
                          }
                          /**
                           * @dev See {IERC20-allowance}.
                           */
                          function allowance(address owner, address spender) public view virtual override returns (uint256) {
                              return _allowances[owner][spender];
                          }
                          /**
                           * @dev See {IERC20-approve}.
                           *
                           * Requirements:
                           *
                           * - `spender` cannot be the zero address.
                           */
                          function approve(address spender, uint256 amount) public virtual override returns (bool) {
                              _approve(_msgSender(), spender, amount);
                              return true;
                          }
                          /**
                           * @dev See {IERC20-transferFrom}.
                           *
                           * Emits an {Approval} event indicating the updated allowance. This is not
                           * required by the EIP. See the note at the beginning of {ERC20}.
                           *
                           * Requirements:
                           *
                           * - `sender` and `recipient` cannot be the zero address.
                           * - `sender` must have a balance of at least `amount`.
                           * - the caller must have allowance for ``sender``'s tokens of at least
                           * `amount`.
                           */
                          function transferFrom(
                              address sender,
                              address recipient,
                              uint256 amount
                          ) public virtual override returns (bool) {
                              _transfer(sender, recipient, amount);
                              uint256 currentAllowance = _allowances[sender][_msgSender()];
                              require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
                              unchecked {
                                  _approve(sender, _msgSender(), currentAllowance - amount);
                              }
                              return true;
                          }
                          /**
                           * @dev Atomically increases the allowance granted to `spender` by the caller.
                           *
                           * This is an alternative to {approve} that can be used as a mitigation for
                           * problems described in {IERC20-approve}.
                           *
                           * Emits an {Approval} event indicating the updated allowance.
                           *
                           * Requirements:
                           *
                           * - `spender` cannot be the zero address.
                           */
                          function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                              _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
                              return true;
                          }
                          /**
                           * @dev Atomically decreases the allowance granted to `spender` by the caller.
                           *
                           * This is an alternative to {approve} that can be used as a mitigation for
                           * problems described in {IERC20-approve}.
                           *
                           * Emits an {Approval} event indicating the updated allowance.
                           *
                           * Requirements:
                           *
                           * - `spender` cannot be the zero address.
                           * - `spender` must have allowance for the caller of at least
                           * `subtractedValue`.
                           */
                          function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                              uint256 currentAllowance = _allowances[_msgSender()][spender];
                              require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
                              unchecked {
                                  _approve(_msgSender(), spender, currentAllowance - subtractedValue);
                              }
                              return true;
                          }
                          /**
                           * @dev Moves `amount` of tokens from `sender` to `recipient`.
                           *
                           * This internal function is equivalent to {transfer}, and can be used to
                           * e.g. implement automatic token fees, slashing mechanisms, etc.
                           *
                           * Emits a {Transfer} event.
                           *
                           * Requirements:
                           *
                           * - `sender` cannot be the zero address.
                           * - `recipient` cannot be the zero address.
                           * - `sender` must have a balance of at least `amount`.
                           */
                          function _transfer(
                              address sender,
                              address recipient,
                              uint256 amount
                          ) internal virtual {
                              require(sender != address(0), "ERC20: transfer from the zero address");
                              require(recipient != address(0), "ERC20: transfer to the zero address");
                              _beforeTokenTransfer(sender, recipient, amount);
                              uint256 senderBalance = _balances[sender];
                              require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
                              unchecked {
                                  _balances[sender] = senderBalance - amount;
                              }
                              _balances[recipient] += amount;
                              emit Transfer(sender, recipient, amount);
                              _afterTokenTransfer(sender, recipient, amount);
                          }
                          /** @dev Creates `amount` tokens and assigns them to `account`, increasing
                           * the total supply.
                           *
                           * Emits a {Transfer} event with `from` set to the zero address.
                           *
                           * Requirements:
                           *
                           * - `account` cannot be the zero address.
                           */
                          function _mint(address account, uint256 amount) internal virtual {
                              require(account != address(0), "ERC20: mint to the zero address");
                              _beforeTokenTransfer(address(0), account, amount);
                              _totalSupply += amount;
                              _balances[account] += amount;
                              emit Transfer(address(0), account, amount);
                              _afterTokenTransfer(address(0), account, amount);
                          }
                          /**
                           * @dev Destroys `amount` tokens from `account`, reducing the
                           * total supply.
                           *
                           * Emits a {Transfer} event with `to` set to the zero address.
                           *
                           * Requirements:
                           *
                           * - `account` cannot be the zero address.
                           * - `account` must have at least `amount` tokens.
                           */
                          function _burn(address account, uint256 amount) internal virtual {
                              require(account != address(0), "ERC20: burn from the zero address");
                              _beforeTokenTransfer(account, address(0), amount);
                              uint256 accountBalance = _balances[account];
                              require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
                              unchecked {
                                  _balances[account] = accountBalance - amount;
                              }
                              _totalSupply -= amount;
                              emit Transfer(account, address(0), amount);
                              _afterTokenTransfer(account, address(0), amount);
                          }
                          /**
                           * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
                           *
                           * This internal function is equivalent to `approve`, and can be used to
                           * e.g. set automatic allowances for certain subsystems, etc.
                           *
                           * Emits an {Approval} event.
                           *
                           * Requirements:
                           *
                           * - `owner` cannot be the zero address.
                           * - `spender` cannot be the zero address.
                           */
                          function _approve(
                              address owner,
                              address spender,
                              uint256 amount
                          ) internal virtual {
                              require(owner != address(0), "ERC20: approve from the zero address");
                              require(spender != address(0), "ERC20: approve to the zero address");
                              _allowances[owner][spender] = amount;
                              emit Approval(owner, spender, amount);
                          }
                          /**
                           * @dev Hook that is called before any transfer of tokens. This includes
                           * minting and burning.
                           *
                           * Calling conditions:
                           *
                           * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                           * will be transferred to `to`.
                           * - when `from` is zero, `amount` tokens will be minted for `to`.
                           * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
                           * - `from` and `to` are never both zero.
                           *
                           * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                           */
                          function _beforeTokenTransfer(
                              address from,
                              address to,
                              uint256 amount
                          ) internal virtual {}
                          /**
                           * @dev Hook that is called after any transfer of tokens. This includes
                           * minting and burning.
                           *
                           * Calling conditions:
                           *
                           * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                           * has been transferred to `to`.
                           * - when `from` is zero, `amount` tokens have been minted for `to`.
                           * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
                           * - `from` and `to` are never both zero.
                           *
                           * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                           */
                          function _afterTokenTransfer(
                              address from,
                              address to,
                              uint256 amount
                          ) internal virtual {}
                      }
                      

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

                      File 6 of 8: 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 7 of 8: 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 8 of 8: Lido
                      // 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 "solidity-bytes-utils/contracts/BytesLib.sol";
                      import "./interfaces/ILido.sol";
                      import "./interfaces/INodeOperatorsRegistry.sol";
                      import "./interfaces/IDepositContract.sol";
                      import "./interfaces/ILidoExecutionLayerRewardsVault.sol";
                      import "./StETH.sol";
                      import "./lib/StakeLimitUtils.sol";
                      interface IERC721 {
                          /// @notice Transfer ownership of an NFT
                          /// @param _from The current owner of the NFT
                          /// @param _to The new owner
                          /// @param _tokenId The NFT to transfer
                          function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
                      }
                      /**
                      * @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 200.
                      *
                      * 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.
                      *
                      * At the moment withdrawals are not possible in the beacon chain and there's no workaround.
                      * Pool will be upgraded to an actual implementation when withdrawals are enabled
                      * (Phase 1.5 or 2 of Eth2 launch, likely late 2022 or 2023).
                      */
                      contract Lido is ILido, StETH, AragonApp {
                          using SafeMath for uint256;
                          using UnstructuredStorage for bytes32;
                          using StakeLimitUnstructuredStorage for bytes32;
                          using StakeLimitUtils for StakeLimitState.Data;
                          /// ACL
                          bytes32 constant public PAUSE_ROLE = keccak256("PAUSE_ROLE");
                          bytes32 constant public RESUME_ROLE = keccak256("RESUME_ROLE");
                          bytes32 constant public STAKING_PAUSE_ROLE = keccak256("STAKING_PAUSE_ROLE");
                          bytes32 constant public STAKING_CONTROL_ROLE = keccak256("STAKING_CONTROL_ROLE");
                          bytes32 constant public MANAGE_FEE = keccak256("MANAGE_FEE");
                          bytes32 constant public MANAGE_WITHDRAWAL_KEY = keccak256("MANAGE_WITHDRAWAL_KEY");
                          bytes32 constant public MANAGE_PROTOCOL_CONTRACTS_ROLE = keccak256("MANAGE_PROTOCOL_CONTRACTS_ROLE");
                          bytes32 constant public BURN_ROLE = keccak256("BURN_ROLE");
                          bytes32 constant public DEPOSIT_ROLE = keccak256("DEPOSIT_ROLE");
                          bytes32 constant public SET_EL_REWARDS_VAULT_ROLE = keccak256("SET_EL_REWARDS_VAULT_ROLE");
                          bytes32 constant public SET_EL_REWARDS_WITHDRAWAL_LIMIT_ROLE = keccak256(
                              "SET_EL_REWARDS_WITHDRAWAL_LIMIT_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;
                          uint256 internal constant TOTAL_BASIS_POINTS = 10000;
                          /// @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");
                          bytes32 internal constant EL_REWARDS_VAULT_POSITION = keccak256("lido.Lido.executionLayerRewardsVault");
                          /// @dev storage slot position of the staking rate limit structure
                          bytes32 internal constant STAKING_STATE_POSITION = keccak256("lido.Lido.stakeLimit");
                          /// @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 percent in basis points of total pooled ether allowed to withdraw from LidoExecutionLayerRewardsVault per LidoOracle report
                          bytes32 internal constant EL_REWARDS_WITHDRAWAL_LIMIT_POSITION = keccak256("lido.Lido.ELRewardsWithdrawalLimit");
                          /// @dev Just a counter of total amount of execution layer rewards received by Lido contract
                          /// Not used in the logic
                          bytes32 internal constant TOTAL_EL_REWARDS_COLLECTED_POSITION = keccak256("lido.Lido.totalELRewardsCollected");
                          /// @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
                          * @param _treasury treasury contract
                          * @param _insuranceFund insurance fund contract
                          * NB: by default, staking and the whole Lido pool are in paused state
                          */
                          function initialize(
                              IDepositContract _depositContract,
                              address _oracle,
                              INodeOperatorsRegistry _operators,
                              address _treasury,
                              address _insuranceFund
                          )
                              public onlyInit
                          {
                              NODE_OPERATORS_REGISTRY_POSITION.setStorageAddress(address(_operators));
                              DEPOSIT_CONTRACT_POSITION.setStorageAddress(address(_depositContract));
                              _setProtocolContracts(_oracle, _treasury, _insuranceFund);
                              initialized();
                          }
                          /**
                          * @notice Stops accepting new Ether to the protocol
                          *
                          * @dev While accepting new Ether is stopped, calls to the `submit` function,
                          * as well as to the default payable function, will revert.
                          *
                          * Emits `StakingPaused` event.
                          */
                          function pauseStaking() external {
                              _auth(STAKING_PAUSE_ROLE);
                              _pauseStaking();
                          }
                          /**
                          * @notice Resumes accepting new Ether to the protocol (if `pauseStaking` was called previously)
                          * NB: Staking could be rate-limited by imposing a limit on the stake amount
                          * at each moment in time, see `setStakingLimit()` and `removeStakingLimit()`
                          *
                          * @dev Preserves staking limit if it was set previously
                          *
                          * Emits `StakingResumed` event
                          */
                          function resumeStaking() external {
                              _auth(STAKING_CONTROL_ROLE);
                              _resumeStaking();
                          }
                          /**
                          * @notice Sets the staking rate limit
                          *
                          * ▲ Stake limit
                          * │.....  .....   ........ ...            ....     ... Stake limit = max
                          * │      .       .        .   .   .      .    . . .
                          * │     .       .              . .  . . .      . .
                          * │            .                .  . . .
                          * │──────────────────────────────────────────────────> Time
                          * │     ^      ^          ^   ^^^  ^ ^ ^     ^^^ ^     Stake events
                          *
                          * @dev Reverts if:
                          * - `_maxStakeLimit` == 0
                          * - `_maxStakeLimit` >= 2^96
                          * - `_maxStakeLimit` < `_stakeLimitIncreasePerBlock`
                          * - `_maxStakeLimit` / `_stakeLimitIncreasePerBlock` >= 2^32 (only if `_stakeLimitIncreasePerBlock` != 0)
                          *
                          * Emits `StakingLimitSet` event
                          *
                          * @param _maxStakeLimit max stake limit value
                          * @param _stakeLimitIncreasePerBlock stake limit increase per single block
                          */
                          function setStakingLimit(uint256 _maxStakeLimit, uint256 _stakeLimitIncreasePerBlock) external {
                              _auth(STAKING_CONTROL_ROLE);
                              STAKING_STATE_POSITION.setStorageStakeLimitStruct(
                                  STAKING_STATE_POSITION.getStorageStakeLimitStruct().setStakingLimit(
                                      _maxStakeLimit,
                                      _stakeLimitIncreasePerBlock
                                  )
                              );
                              emit StakingLimitSet(_maxStakeLimit, _stakeLimitIncreasePerBlock);
                          }
                          /**
                          * @notice Removes the staking rate limit
                          *
                          * Emits `StakingLimitRemoved` event
                          */
                          function removeStakingLimit() external {
                              _auth(STAKING_CONTROL_ROLE);
                              STAKING_STATE_POSITION.setStorageStakeLimitStruct(
                                  STAKING_STATE_POSITION.getStorageStakeLimitStruct().removeStakingLimit()
                              );
                              emit StakingLimitRemoved();
                          }
                          /**
                          * @notice Check staking state: whether it's paused or not
                          */
                          function isStakingPaused() external view returns (bool) {
                              return STAKING_STATE_POSITION.getStorageStakeLimitStruct().isStakingPaused();
                          }
                          /**
                          * @notice Returns how much Ether can be staked in the current block
                          * @dev Special return values:
                          * - 2^256 - 1 if staking is unlimited;
                          * - 0 if staking is paused or if limit is exhausted.
                          */
                          function getCurrentStakeLimit() public view returns (uint256) {
                              return _getCurrentStakeLimit(STAKING_STATE_POSITION.getStorageStakeLimitStruct());
                          }
                          /**
                          * @notice Returns full info about current stake limit params and state
                          * @dev Might be used for the advanced integration requests.
                          * @return isStakingPaused staking pause state (equivalent to return of isStakingPaused())
                          * @return isStakingLimitSet whether the stake limit is set
                          * @return currentStakeLimit current stake limit (equivalent to return of getCurrentStakeLimit())
                          * @return maxStakeLimit max stake limit
                          * @return maxStakeLimitGrowthBlocks blocks needed to restore max stake limit from the fully exhausted state
                          * @return prevStakeLimit previously reached stake limit
                          * @return prevStakeBlockNumber previously seen block number
                          */
                          function getStakeLimitFullInfo() external view returns (
                              bool isStakingPaused,
                              bool isStakingLimitSet,
                              uint256 currentStakeLimit,
                              uint256 maxStakeLimit,
                              uint256 maxStakeLimitGrowthBlocks,
                              uint256 prevStakeLimit,
                              uint256 prevStakeBlockNumber
                          ) {
                              StakeLimitState.Data memory stakeLimitData = STAKING_STATE_POSITION.getStorageStakeLimitStruct();
                              isStakingPaused = stakeLimitData.isStakingPaused();
                              isStakingLimitSet = stakeLimitData.isStakingLimitSet();
                              currentStakeLimit = _getCurrentStakeLimit(stakeLimitData);
                              maxStakeLimit = stakeLimitData.maxStakeLimit;
                              maxStakeLimitGrowthBlocks = stakeLimitData.maxStakeLimitGrowthBlocks;
                              prevStakeLimit = stakeLimitData.prevStakeLimit;
                              prevStakeBlockNumber = stakeLimitData.prevStakeBlockNumber;
                          }
                          /**
                          * @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 A payable function for execution layer rewards. Can be called only by ExecutionLayerRewardsVault contract
                          * @dev We need a dedicated function because funds received by the default payable function
                          * are treated as a user deposit
                          */
                          function receiveELRewards() external payable {
                              require(msg.sender == EL_REWARDS_VAULT_POSITION.getStorageAddress());
                              TOTAL_EL_REWARDS_COLLECTED_POSITION.setStorageUint256(
                                  TOTAL_EL_REWARDS_COLLECTED_POSITION.getStorageUint256().add(msg.value));
                              emit ELRewardsReceived(msg.value);
                          }
                          /**
                          * @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();
                              _pauseStaking();
                          }
                          /**
                          * @notice Resume pool routine operations
                          * @dev Staking should be resumed manually after this call using the desired limits
                          */
                          function resume() external {
                              _auth(RESUME_ROLE);
                              _resume();
                              _resumeStaking();
                          }
                          /**
                          * @notice Set fee rate to `_feeBasisPoints` basis points.
                          * The fees are accrued when:
                          * - oracles report staking results (beacon chain balance increase)
                          * - validators gain execution layer rewards (priority fees and MEV)
                          * @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
                          * @param _treasuryFeeBasisPoints basis points go to the treasury,
                          * @param _insuranceFeeBasisPoints basis points go to the insurance fund,
                          * @param _operatorsFeeBasisPoints basis points go to node operators.
                          * @dev The sum has to be 10 000.
                          */
                          function setFeeDistribution(
                              uint16 _treasuryFeeBasisPoints,
                              uint16 _insuranceFeeBasisPoints,
                              uint16 _operatorsFeeBasisPoints
                          )
                              external
                          {
                              _auth(MANAGE_FEE);
                              require(
                                  TOTAL_BASIS_POINTS == 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 Lido protocol contracts (oracle, treasury, insurance fund).
                          *
                          * @dev Oracle contract specified here is allowed to make
                          * periodical updates of beacon stats
                          * by calling pushBeacon. Treasury contract specified here is used
                          * to accumulate the protocol treasury fee. Insurance fund contract
                          * specified here is used to accumulate the protocol insurance fee.
                          *
                          * @param _oracle oracle contract
                          * @param _treasury treasury contract
                          * @param _insuranceFund insurance fund contract
                          */
                          function setProtocolContracts(
                              address _oracle,
                              address _treasury,
                              address _insuranceFund
                          ) external {
                              _auth(MANAGE_PROTOCOL_CONTRACTS_ROLE);
                              _setProtocolContracts(_oracle, _treasury, _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 withdrawal credentials field as defined in the Ethereum PoS consensus specs
                          */
                          function setWithdrawalCredentials(bytes32 _withdrawalCredentials) external {
                              _auth(MANAGE_WITHDRAWAL_KEY);
                              WITHDRAWAL_CREDENTIALS_POSITION.setStorageBytes32(_withdrawalCredentials);
                              getOperators().trimUnusedKeys();
                              emit WithdrawalCredentialsSet(_withdrawalCredentials);
                          }
                          /**
                          * @dev Sets the address of LidoExecutionLayerRewardsVault contract
                          * @param _executionLayerRewardsVault Execution layer rewards vault contract address
                          */
                          function setELRewardsVault(address _executionLayerRewardsVault) external {
                              _auth(SET_EL_REWARDS_VAULT_ROLE);
                              EL_REWARDS_VAULT_POSITION.setStorageAddress(_executionLayerRewardsVault);
                              emit ELRewardsVaultSet(_executionLayerRewardsVault);
                          }
                          /**
                          * @dev Sets limit on amount of ETH to withdraw from execution layer rewards vault per LidoOracle report
                          * @param _limitPoints limit in basis points to amount of ETH to withdraw per LidoOracle report
                          */
                          function setELRewardsWithdrawalLimit(uint16 _limitPoints) external {
                              _auth(SET_EL_REWARDS_WITHDRAWAL_LIMIT_ROLE);
                              _setBPValue(EL_REWARDS_WITHDRAWAL_LIMIT_POSITION, _limitPoints);
                              emit ELRewardsWithdrawalLimitSet(_limitPoints);
                          }
                          /**
                          * @notice Updates beacon stats, collects rewards from LidoExecutionLayerRewardsVault and distributes all rewards if beacon balance increased
                          * @dev periodically called by the Oracle contract
                          * @param _beaconValidators number of Lido's keys in the beacon state
                          * @param _beaconBalance summarized balance of Lido-controlled keys in wei
                          */
                          function handleOracleReport(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
                              // calculate rewards on the next push
                              BEACON_BALANCE_POSITION.setStorageUint256(_beaconBalance);
                              BEACON_VALIDATORS_POSITION.setStorageUint256(_beaconValidators);
                              // If LidoExecutionLayerRewardsVault address is not set just do as if there were no execution layer rewards at all
                              // Otherwise withdraw all rewards and put them to the buffer
                              // Thus, execution layer rewards are handled the same way as beacon rewards
                              uint256 executionLayerRewards;
                              address executionLayerRewardsVaultAddress = getELRewardsVault();
                              if (executionLayerRewardsVaultAddress != address(0)) {
                                  executionLayerRewards = ILidoExecutionLayerRewardsVault(executionLayerRewardsVaultAddress).withdrawRewards(
                                      (_getTotalPooledEther() * EL_REWARDS_WITHDRAWAL_LIMIT_POSITION.getStorageUint256()) / TOTAL_BASIS_POINTS
                                  );
                                  if (executionLayerRewards != 0) {
                                      BUFFERED_ETHER_POSITION.setStorageUint256(_getBufferedEther().add(executionLayerRewards));
                                  }
                              }
                              // Don’t mint/distribute any protocol fee on the non-profitable Lido oracle report
                              // (when beacon chain balance delta is zero or negative).
                              // See ADR #3 for details: https://research.lido.fi/t/rewards-distribution-after-the-merge-architecture-decision-record/1535
                              if (_beaconBalance > rewardBase) {
                                  uint256 rewards = _beaconBalance.sub(rewardBase);
                                  distributeFee(rewards.add(executionLayerRewards));
                              }
                          }
                          /**
                          * @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(vault != address(0), "RECOVER_VAULT_ZERO");
                              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 overridden default implementation
                                  require(token.safeTransfer(vault, balance), "RECOVER_TOKEN_TRANSFER_FAILED");
                              }
                              emit RecoverToVault(vault, _token, balance);
                          }
                          /**
                          * @notice Returns staking rewards fee rate
                          */
                          function getFee() public view returns (uint16 feeBasisPoints) {
                              return uint16(FEE_POSITION.getStorageUint256());
                          }
                          /**
                          * @notice Returns fee distribution proportion
                          */
                          function getFeeDistribution()
                              public
                              view
                              returns (
                                  uint16 treasuryFeeBasisPoints,
                                  uint16 insuranceFeeBasisPoints,
                                  uint16 operatorsFeeBasisPoints
                              )
                          {
                              treasuryFeeBasisPoints = uint16(TREASURY_FEE_POSITION.getStorageUint256());
                              insuranceFeeBasisPoints = uint16(INSURANCE_FEE_POSITION.getStorageUint256());
                              operatorsFeeBasisPoints = uint16(NODE_OPERATORS_FEE_POSITION.getStorageUint256());
                          }
                          /**
                          * @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 amount of buffered funds in wei
                          */
                          function getBufferedEther() external view returns (uint256) {
                              return _getBufferedEther();
                          }
                          /**
                          * @notice Get total amount of execution layer rewards collected to Lido contract
                          * @dev Ether got through LidoExecutionLayerRewardsVault is kept on this contract's balance the same way
                          * as other buffered Ether is kept (until it gets deposited)
                          * @return amount of funds received as execution layer rewards (in wei)
                          */
                          function getTotalELRewardsCollected() external view returns (uint256) {
                              return TOTAL_EL_REWARDS_COLLECTED_POSITION.getStorageUint256();
                          }
                          /**
                          * @notice Get limit in basis points to amount of ETH to withdraw per LidoOracle report
                          * @return limit in basis points to amount of ETH to withdraw per LidoOracle report
                          */
                          function getELRewardsWithdrawalLimit() external view returns (uint256) {
                              return EL_REWARDS_WITHDRAWAL_LIMIT_POSITION.getStorageUint256();
                          }
                          /**
                          * @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();
                          }
                          /**
                          * @notice Returns address of the contract set as LidoExecutionLayerRewardsVault
                          */
                          function getELRewardsVault() public view returns (address) {
                              return EL_REWARDS_VAULT_POSITION.getStorageAddress();
                          }
                          /**
                          * @dev Internal function to set authorized oracle address
                          * @param _oracle oracle contract
                          */
                          function _setProtocolContracts(address _oracle, address _treasury, address _insuranceFund) internal {
                              require(_oracle != address(0), "ORACLE_ZERO_ADDRESS");
                              require(_treasury != address(0), "TREASURY_ZERO_ADDRESS");
                              require(_insuranceFund != address(0), "INSURANCE_FUND_ZERO_ADDRESS");
                              ORACLE_POSITION.setStorageAddress(_oracle);
                              TREASURY_POSITION.setStorageAddress(_treasury);
                              INSURANCE_FUND_POSITION.setStorageAddress(_insuranceFund);
                              emit ProtocolContactsSet(_oracle, _treasury, _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 returns (uint256) {
                              require(msg.value != 0, "ZERO_DEPOSIT");
                              StakeLimitState.Data memory stakeLimitData = STAKING_STATE_POSITION.getStorageStakeLimitStruct();
                              require(!stakeLimitData.isStakingPaused(), "STAKING_PAUSED");
                              if (stakeLimitData.isStakingLimitSet()) {
                                  uint256 currentStakeLimit = stakeLimitData.calculateCurrentStakeLimit();
                                  require(msg.value <= currentStakeLimit, "STAKE_LIMIT");
                                  STAKING_STATE_POSITION.setStorageStakeLimitStruct(
                                      stakeLimitData.updatePrevStakeLimit(currentStakeLimit - msg.value)
                                  );
                              }
                              uint256 sharesAmount = getSharesByPooledEth(msg.value);
                              if (sharesAmount == 0) {
                                  // totalControlledEther is 0: either the first-ever deposit or complete slashing
                                  // assume that shares correspond to Ether 1-to-1
                                  sharesAmount = msg.value;
                              }
                              _mintShares(msg.sender, sharesAmount);
                              BUFFERED_ETHER_POSITION.setStorageUint256(_getBufferedEther().add(msg.value));
                              emit Submitted(msg.sender, msg.value, _referral);
                              _emitTransferAfterMintingShares(msg.sender, sharesAmount);
                              return sharesAmount;
                          }
                          /**
                          * @dev Emits {Transfer} and {TransferShares} events where `from` is 0 address. Indicates mint events.
                          */
                          function _emitTransferAfterMintingShares(address _to, uint256 _sharesAmount) internal {
                              emit Transfer(address(0), _to, getPooledEthByShares(_sharesAmount));
                              emit TransferShares(address(0), _to, _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 fee portion of the rewards by minting and distributing corresponding amount of liquid tokens.
                          * @param _totalRewards Total rewards accrued on the Ethereum 2.0 side in wei
                          */
                          function distributeFee(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 (TOTAL_BASIS_POINTS) 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) / TOTAL_BASIS_POINTS
                              // newShareCost = newTotalPooledEther / (prevTotalShares + shares2mint)
                              //
                              // which follows to:
                              //
                              //                        _totalRewards * feeBasis * prevTotalShares
                              // shares2mint = --------------------------------------------------------------
                              //                 (newTotalPooledEther * TOTAL_BASIS_POINTS) - (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(TOTAL_BASIS_POINTS)
                                      .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(TOTAL_BASIS_POINTS);
                              address insuranceFund = getInsuranceFund();
                              _transferShares(address(this), insuranceFund, toInsuranceFund);
                              _emitTransferAfterMintingShares(insuranceFund, toInsuranceFund);
                              uint256 distributedToOperatorsShares = _distributeNodeOperatorsReward(
                                  shares2mint.mul(operatorsFeeBasisPoints).div(TOTAL_BASIS_POINTS)
                              );
                              // 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);
                          }
                          /**
                          *  @dev Internal function to distribute reward to node operators
                          *  @param _sharesToDistribute amount of shares to distribute
                          *  @return actual amount of shares that was transferred to node operators as a reward
                          */
                          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 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 <= TOTAL_BASIS_POINTS, "VALUE_OVER_100_PERCENT");
                              _slot.setStorageUint256(uint256(_value));
                          }
                          /**
                          * @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);
                              return depositedValidators.sub(beaconValidators).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) {
                              return _getBufferedEther().add(
                                  BEACON_BALANCE_POSITION.getStorageUint256()
                              ).add(_getTransientBalance());
                          }
                          /**
                          * @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 _pauseStaking() internal {
                              STAKING_STATE_POSITION.setStorageStakeLimitStruct(
                                  STAKING_STATE_POSITION.getStorageStakeLimitStruct().setStakeLimitPauseState(true)
                              );
                              emit StakingPaused();
                          }
                          function _resumeStaking() internal {
                              STAKING_STATE_POSITION.setStorageStakeLimitStruct(
                                  STAKING_STATE_POSITION.getStorageStakeLimitStruct().setStakeLimitPauseState(false)
                              );
                              emit StakingResumed();
                          }
                          function _getCurrentStakeLimit(StakeLimitState.Data memory _stakeLimitData) internal view returns(uint256) {
                              if (_stakeLimitData.isStakingPaused()) {
                                  return 0;
                              }
                              if (!_stakeLimitData.isStakingLimitSet()) {
                                  return uint256(-1);
                              }
                              return _stakeLimitData.calculateCurrentStakeLimit();
                          }
                          /**
                          * @dev Size-efficient analog of the `auth(_role)` modifier
                          * @param _role Permission name
                          */
                          function _auth(bytes32 _role) internal view auth(_role) {
                              // no-op
                          }
                      }
                      /*
                       * 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;
                          }
                      }
                      /*
                       * @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.
                        *
                        * At the moment withdrawals are not possible in the beacon chain and there's no workaround.
                        * Pool will be upgraded to an actual implementation when withdrawals are enabled
                        * (Phase 1.5 or 2 of Eth2 launch, likely late 2022 or 2023).
                        */
                      interface ILido {
                          function totalSupply() external view returns (uint256);
                          function getTotalShares() external view returns (uint256);
                          /**
                            * @notice Stop pool routine operations
                            */
                          function stop() external;
                          /**
                            * @notice Resume pool routine operations
                            */
                          function resume() external;
                          /**
                            * @notice Stops accepting new Ether to the protocol
                            *
                            * @dev While accepting new Ether is stopped, calls to the `submit` function,
                            * as well as to the default payable function, will revert.
                            *
                            * Emits `StakingPaused` event.
                            */
                          function pauseStaking() external;
                          /**
                            * @notice Resumes accepting new Ether to the protocol (if `pauseStaking` was called previously)
                            * NB: Staking could be rate-limited by imposing a limit on the stake amount
                            * at each moment in time, see `setStakingLimit()` and `removeStakingLimit()`
                            *
                            * @dev Preserves staking limit if it was set previously
                            *
                            * Emits `StakingResumed` event
                            */
                          function resumeStaking() external;
                          /**
                            * @notice Sets the staking rate limit
                            *
                            * @dev Reverts if:
                            * - `_maxStakeLimit` == 0
                            * - `_maxStakeLimit` >= 2^96
                            * - `_maxStakeLimit` < `_stakeLimitIncreasePerBlock`
                            * - `_maxStakeLimit` / `_stakeLimitIncreasePerBlock` >= 2^32 (only if `_stakeLimitIncreasePerBlock` != 0)
                            *
                            * Emits `StakingLimitSet` event
                            *
                            * @param _maxStakeLimit max stake limit value
                            * @param _stakeLimitIncreasePerBlock stake limit increase per single block
                            */
                          function setStakingLimit(uint256 _maxStakeLimit, uint256 _stakeLimitIncreasePerBlock) external;
                          /**
                            * @notice Removes the staking rate limit
                            *
                            * Emits `StakingLimitRemoved` event
                            */
                          function removeStakingLimit() external;
                          /**
                            * @notice Check staking state: whether it's paused or not
                            */
                          function isStakingPaused() external view returns (bool);
                          /**
                            * @notice Returns how much Ether can be staked in the current block
                            * @dev Special return values:
                            * - 2^256 - 1 if staking is unlimited;
                            * - 0 if staking is paused or if limit is exhausted.
                            */
                          function getCurrentStakeLimit() external view returns (uint256);
                          /**
                            * @notice Returns full info about current stake limit params and state
                            * @dev Might be used for the advanced integration requests.
                            * @return isStakingPaused staking pause state (equivalent to return of isStakingPaused())
                            * @return isStakingLimitSet whether the stake limit is set
                            * @return currentStakeLimit current stake limit (equivalent to return of getCurrentStakeLimit())
                            * @return maxStakeLimit max stake limit
                            * @return maxStakeLimitGrowthBlocks blocks needed to restore max stake limit from the fully exhausted state
                            * @return prevStakeLimit previously reached stake limit
                            * @return prevStakeBlockNumber previously seen block number
                            */
                          function getStakeLimitFullInfo() external view returns (
                              bool isStakingPaused,
                              bool isStakingLimitSet,
                              uint256 currentStakeLimit,
                              uint256 maxStakeLimit,
                              uint256 maxStakeLimitGrowthBlocks,
                              uint256 prevStakeLimit,
                              uint256 prevStakeBlockNumber
                          );
                          event Stopped();
                          event Resumed();
                          event StakingPaused();
                          event StakingResumed();
                          event StakingLimitSet(uint256 maxStakeLimit, uint256 stakeLimitIncreasePerBlock);
                          event StakingLimitRemoved();
                          /**
                            * @notice Set Lido protocol contracts (oracle, treasury, insurance fund).
                            * @param _oracle oracle contract
                            * @param _treasury treasury contract
                            * @param _insuranceFund insurance fund contract
                            */
                          function setProtocolContracts(
                              address _oracle,
                              address _treasury,
                              address _insuranceFund
                          ) external;
                          event ProtocolContactsSet(address oracle, address treasury, address insuranceFund);
                          /**
                            * @notice Set fee rate to `_feeBasisPoints` basis points.
                            * The fees are accrued when:
                            * - oracles report staking results (beacon chain balance increase)
                            * - validators gain execution layer rewards (priority fees and MEV)
                            * @param _feeBasisPoints Fee rate, in basis points
                            */
                          function setFee(uint16 _feeBasisPoints) external;
                          /**
                            * @notice Set fee distribution
                            * @param _treasuryFeeBasisPoints basis points go to the treasury,
                            * @param _insuranceFeeBasisPoints basis points go to the insurance fund,
                            * @param _operatorsFeeBasisPoints basis points go to node operators.
                            * @dev 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 A payable function supposed to be called only by LidoExecutionLayerRewardsVault contract
                            * @dev We need a dedicated function because funds received by the default payable function
                            * are treated as a user deposit
                            */
                          function receiveELRewards() external payable;
                          // The amount of ETH withdrawn from LidoExecutionLayerRewardsVault contract to Lido contract
                          event ELRewardsReceived(uint256 amount);
                          /**
                            * @dev Sets limit on amount of ETH to withdraw from execution layer rewards vault per LidoOracle report
                            * @param _limitPoints limit in basis points to amount of ETH to withdraw per LidoOracle report
                            */
                          function setELRewardsWithdrawalLimit(uint16 _limitPoints) external;
                          // Percent in basis points of total pooled ether allowed to withdraw from LidoExecutionLayerRewardsVault per LidoOracle report
                          event ELRewardsWithdrawalLimitSet(uint256 limitPoints);
                          /**
                            * @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 withdrawal credentials field as defined in the Ethereum PoS consensus specs
                            */
                          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);
                          /**
                            * @dev Sets the address of LidoExecutionLayerRewardsVault contract
                            * @param _executionLayerRewardsVault Execution layer rewards vault contract address
                            */
                          function setELRewardsVault(address _executionLayerRewardsVault) external;
                          // The `executionLayerRewardsVault` was set as the execution layer rewards vault for Lido
                          event ELRewardsVaultSet(address executionLayerRewardsVault);
                          /**
                            * @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 handleOracleReport(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);
                          // 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 = 0 validators
                            * @param _name Human-readable name
                            * @param _rewardAddress Ethereum 1 address which receives stETH rewards for this operator
                            * @return a unique key of the added operator
                            */
                          function addNodeOperator(string _name, address _rewardAddress) 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);
                          event NodeOperatorTotalKeysTrimmed(uint256 indexed id, uint64 totalKeysTrimmed);
                          /**
                           * @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 Add `_quantity` validator signing keys of operator #`_id` to the set of usable keys. Concatenated keys are: `_pubkeys`. Can be done by node operator in question by using the designated rewards address.
                            * @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 addSigningKeysOperatorBH(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 Removes a validator signing key #`_index` of operator #`_id` from the set of usable keys. Executed on behalf of Node Operator.
                            * @param _operator_id Node Operator id
                            * @param _index Index of the key, starting with 0
                            */
                          function removeSigningKeyOperatorBH(uint256 _operator_id, uint256 _index) external;
                          /**
                            * @notice Removes an #`_amount` of validator signing keys starting from #`_index` of operator #`_id` usable keys. Executed on behalf of DAO.
                            * @param _operator_id Node Operator id
                            * @param _index Index of the key, starting with 0
                            * @param _amount Number of keys to remove
                            */
                          function removeSigningKeys(uint256 _operator_id, uint256 _index, uint256 _amount) external;
                          /**
                            * @notice Removes an #`_amount` of validator signing keys starting from #`_index` of operator #`_id` usable keys. Executed on behalf of Node Operator.
                            * @param _operator_id Node Operator id
                            * @param _index Index of the key, starting with 0
                            * @param _amount Number of keys to remove
                            */
                          function removeSigningKeysOperatorBH(uint256 _operator_id, uint256 _index, uint256 _amount) 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);
                          /**
                           * @notice Returns a monotonically increasing counter that gets incremented when any of the following happens:
                           *   1. a node operator's key(s) is added;
                           *   2. a node operator's key(s) is removed;
                           *   3. a node operator's approved keys limit is changed.
                           *   4. a node operator was activated/deactivated. Activation or deactivation of node operator
                           *      might lead to usage of unvalidated keys in the assignNextSigningKeys method.
                           */
                          function getKeysOpIndex() external view returns (uint256);
                          event SigningKeyAdded(uint256 indexed operatorId, bytes pubkey);
                          event SigningKeyRemoved(uint256 indexed operatorId, bytes pubkey);
                          event KeysOpIndexSet(uint256 keysOpIndex);
                      }
                      // 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: 2021 Lido <[email protected]>
                      // SPDX-License-Identifier: GPL-3.0
                      pragma solidity 0.4.24;
                      interface ILidoExecutionLayerRewardsVault {
                          /**
                          * @notice Withdraw all accumulated execution layer rewards to Lido contract
                          * @param _maxAmount Max amount of ETH to withdraw
                          * @return amount of funds received as execution layer rewards (in wei)
                          */
                          function withdrawRewards(uint256 _maxAmount) external returns (uint256 amount);
                      }
                      // 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 overridden
                       * 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");
                          /**
                            * @notice An executed shares transfer from `sender` to `recipient`.
                            *
                            * @dev emitted in pair with an ERC20-defined `Transfer` event.
                            */
                          event TransferShares(
                              address indexed from,
                              address indexed to,
                              uint256 sharesValue
                          );
                          /**
                           * @notice An executed `burnShares` request
                           *
                           * @dev Reports simultaneously burnt shares amount
                           * and corresponding stETH amount.
                           * The stETH amount is calculated twice: before and after the burning incurred rebase.
                           *
                           * @param account holder of the burnt shares
                           * @param preRebaseTokenAmount amount of stETH the burnt shares corresponded to before the burn
                           * @param postRebaseTokenAmount amount of stETH the burnt shares corresponded to after the burn
                           * @param sharesAmount amount of burnt shares
                           */
                          event SharesBurnt(
                              address indexed account,
                              uint256 preRebaseTokenAmount,
                              uint256 postRebaseTokenAmount,
                              uint256 sharesAmount
                          );
                          /**
                           * @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.
                           * Emits a `TransferShares` 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 a `TransferShares` 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);
                              }
                          }
                          /**
                           * @notice Moves `_sharesAmount` token shares from the caller's account to the `_recipient` account.
                           *
                           * @return amount of transferred tokens.
                           * Emits a `TransferShares` event.
                           * Emits a `Transfer` event.
                           *
                           * Requirements:
                           *
                           * - `_recipient` cannot be the zero address.
                           * - the caller must have at least `_sharesAmount` shares.
                           * - the contract must not be paused.
                           *
                           * @dev The `_sharesAmount` argument is the amount of shares, not tokens.
                           */
                          function transferShares(address _recipient, uint256 _sharesAmount) public returns (uint256) {
                              _transferShares(msg.sender, _recipient, _sharesAmount);
                              emit TransferShares(msg.sender, _recipient, _sharesAmount);
                              uint256 tokensAmount = getPooledEthByShares(_sharesAmount);
                              emit Transfer(msg.sender, _recipient, tokensAmount);
                              return tokensAmount;
                          }
                          /**
                           * @return the total amount (in wei) of Ether controlled by the protocol.
                           * @dev This is used for calculating 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.
                           * Emits a `TransferShares` event.
                           */
                          function _transfer(address _sender, address _recipient, uint256 _amount) internal {
                              uint256 _sharesToTransfer = getSharesByPooledEth(_amount);
                              _transferShares(_sender, _recipient, _sharesToTransfer);
                              emit Transfer(_sender, _recipient, _amount);
                              emit TransferShares(_sender, _recipient, _sharesToTransfer);
                          }
                          /**
                           * @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");
                              uint256 preRebaseTokenAmount = getPooledEthByShares(_sharesAmount);
                              newTotalShares = _getTotalShares().sub(_sharesAmount);
                              TOTAL_SHARES_POSITION.setStorageUint256(newTotalShares);
                              shares[_account] = accountShares.sub(_sharesAmount);
                              uint256 postRebaseTokenAmount = getPooledEthByShares(_sharesAmount);
                              emit SharesBurnt(_account, preRebaseTokenAmount, postRebaseTokenAmount, _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.
                              // We're emitting `SharesBurnt` event to provide an explicit rebase log record nonetheless.
                          }
                      }
                      // SPDX-FileCopyrightText: 2022 Lido <[email protected]>
                      // SPDX-License-Identifier: GPL-3.0
                      /* See contracts/COMPILERS.md */
                      pragma solidity 0.4.24;
                      import "@aragon/os/contracts/common/UnstructuredStorage.sol";
                      //
                      // We need to pack four variables into the same 256bit-wide storage slot
                      // to lower the costs per each staking request.
                      //
                      // As a result, slot's memory aligned as follows:
                      //
                      // MSB ------------------------------------------------------------------------------> LSB
                      // 256____________160_________________________128_______________32_____________________ 0
                      // |_______________|___________________________|________________|_______________________|
                      // | maxStakeLimit | maxStakeLimitGrowthBlocks | prevStakeLimit | prevStakeBlockNumber  |
                      // |<-- 96 bits -->|<---------- 32 bits ------>|<-- 96 bits --->|<----- 32 bits ------->|
                      //
                      //
                      // NB: Internal representation conventions:
                      //
                      // - the `maxStakeLimitGrowthBlocks` field above represented as follows:
                      // `maxStakeLimitGrowthBlocks` = `maxStakeLimit` / `stakeLimitIncreasePerBlock`
                      //           32 bits                 96 bits               96 bits
                      //
                      //
                      // - the "staking paused" state is encoded by `prevStakeBlockNumber` being zero,
                      // - the "staking unlimited" state is encoded by `maxStakeLimit` being zero and `prevStakeBlockNumber` being non-zero.
                      //
                      /**
                      * @notice Library for the internal structs definitions
                      * @dev solidity <0.6 doesn't support top-level structs
                      * using the library to have a proper namespace
                      */
                      library StakeLimitState {
                          /**
                            * @dev Internal representation struct (slot-wide)
                            */
                          struct Data {
                              uint32 prevStakeBlockNumber;
                              uint96 prevStakeLimit;
                              uint32 maxStakeLimitGrowthBlocks;
                              uint96 maxStakeLimit;
                          }
                      }
                      library StakeLimitUnstructuredStorage {
                          using UnstructuredStorage for bytes32;
                          /// @dev Storage offset for `maxStakeLimit` (bits)
                          uint256 internal constant MAX_STAKE_LIMIT_OFFSET = 160;
                          /// @dev Storage offset for `maxStakeLimitGrowthBlocks` (bits)
                          uint256 internal constant MAX_STAKE_LIMIT_GROWTH_BLOCKS_OFFSET = 128;
                          /// @dev Storage offset for `prevStakeLimit` (bits)
                          uint256 internal constant PREV_STAKE_LIMIT_OFFSET = 32;
                          /// @dev Storage offset for `prevStakeBlockNumber` (bits)
                          uint256 internal constant PREV_STAKE_BLOCK_NUMBER_OFFSET = 0;
                          /**
                          * @dev Read stake limit state from the unstructured storage position
                          * @param _position storage offset
                          */
                          function getStorageStakeLimitStruct(bytes32 _position) internal view returns (StakeLimitState.Data memory stakeLimit) {
                              uint256 slotValue = _position.getStorageUint256();
                              stakeLimit.prevStakeBlockNumber = uint32(slotValue >> PREV_STAKE_BLOCK_NUMBER_OFFSET);
                              stakeLimit.prevStakeLimit = uint96(slotValue >> PREV_STAKE_LIMIT_OFFSET);
                              stakeLimit.maxStakeLimitGrowthBlocks = uint32(slotValue >> MAX_STAKE_LIMIT_GROWTH_BLOCKS_OFFSET);
                              stakeLimit.maxStakeLimit = uint96(slotValue >> MAX_STAKE_LIMIT_OFFSET);
                          }
                           /**
                          * @dev Write stake limit state to the unstructured storage position
                          * @param _position storage offset
                          * @param _data stake limit state structure instance
                          */
                          function setStorageStakeLimitStruct(bytes32 _position, StakeLimitState.Data memory _data) internal {
                              _position.setStorageUint256(
                                  uint256(_data.prevStakeBlockNumber) << PREV_STAKE_BLOCK_NUMBER_OFFSET
                                      | uint256(_data.prevStakeLimit) << PREV_STAKE_LIMIT_OFFSET
                                      | uint256(_data.maxStakeLimitGrowthBlocks) << MAX_STAKE_LIMIT_GROWTH_BLOCKS_OFFSET
                                      | uint256(_data.maxStakeLimit) << MAX_STAKE_LIMIT_OFFSET
                              );
                          }
                      }
                      /**
                      * @notice Interface library with helper functions to deal with stake limit struct in a more high-level approach.
                      */
                      library StakeLimitUtils {
                          /**
                          * @notice Calculate stake limit for the current block.
                          */
                          function calculateCurrentStakeLimit(StakeLimitState.Data memory _data) internal view returns(uint256 limit) {
                              uint256 stakeLimitIncPerBlock;
                              if (_data.maxStakeLimitGrowthBlocks != 0) {
                                  stakeLimitIncPerBlock = _data.maxStakeLimit / _data.maxStakeLimitGrowthBlocks;
                              }
                              limit = _data.prevStakeLimit + ((block.number - _data.prevStakeBlockNumber) * stakeLimitIncPerBlock);
                              if (limit > _data.maxStakeLimit) {
                                  limit = _data.maxStakeLimit;
                              }
                          }
                          /**
                          * @notice check if staking is on pause
                          */
                          function isStakingPaused(StakeLimitState.Data memory _data) internal pure returns(bool) {
                              return _data.prevStakeBlockNumber == 0;
                          }
                          /**
                          * @notice check if staking limit is set (otherwise staking is unlimited)
                          */
                          function isStakingLimitSet(StakeLimitState.Data memory _data) internal pure returns(bool) {
                              return _data.maxStakeLimit != 0;
                          }
                          /**
                          * @notice update stake limit repr with the desired limits
                          * @dev input `_data` param is mutated and the func returns effectively the same pointer
                          * @param _data stake limit state struct
                          * @param _maxStakeLimit stake limit max value
                          * @param _stakeLimitIncreasePerBlock stake limit increase (restoration) per block
                          */
                          function setStakingLimit(
                              StakeLimitState.Data memory _data,
                              uint256 _maxStakeLimit,
                              uint256 _stakeLimitIncreasePerBlock
                          ) internal view returns (StakeLimitState.Data memory) {
                              require(_maxStakeLimit != 0, "ZERO_MAX_STAKE_LIMIT");
                              require(_maxStakeLimit <= uint96(-1), "TOO_LARGE_MAX_STAKE_LIMIT");
                              require(_maxStakeLimit >= _stakeLimitIncreasePerBlock, "TOO_LARGE_LIMIT_INCREASE");
                              require(
                                  (_stakeLimitIncreasePerBlock == 0)
                                  || (_maxStakeLimit / _stakeLimitIncreasePerBlock <= uint32(-1)),
                                  "TOO_SMALL_LIMIT_INCREASE"
                              );
                              // if staking was paused or unlimited previously,
                              // or new limit is lower than previous, then
                              // reset prev stake limit to the new max stake limit
                              if ((_data.maxStakeLimit == 0) || (_maxStakeLimit < _data.prevStakeLimit)) {
                                  _data.prevStakeLimit = uint96(_maxStakeLimit);
                              }
                              _data.maxStakeLimitGrowthBlocks = _stakeLimitIncreasePerBlock != 0 ? uint32(_maxStakeLimit / _stakeLimitIncreasePerBlock) : 0;
                              _data.maxStakeLimit = uint96(_maxStakeLimit);
                              if (_data.prevStakeBlockNumber != 0) {
                                  _data.prevStakeBlockNumber = uint32(block.number);
                              }
                              return _data;
                          }
                          /**
                          * @notice update stake limit repr to remove the limit
                          * @dev input `_data` param is mutated and the func returns effectively the same pointer
                          * @param _data stake limit state struct
                          */
                          function removeStakingLimit(
                              StakeLimitState.Data memory _data
                          ) internal view returns (StakeLimitState.Data memory) {
                              _data.maxStakeLimit = 0;
                              return _data;
                          }
                          /**
                          * @notice update stake limit repr after submitting user's eth
                          * @dev input `_data` param is mutated and the func returns effectively the same pointer
                          * @param _data stake limit state struct
                          * @param _newPrevStakeLimit new value for the `prevStakeLimit` field
                          */
                          function updatePrevStakeLimit(
                              StakeLimitState.Data memory _data,
                              uint256 _newPrevStakeLimit
                          ) internal view returns (StakeLimitState.Data memory) {
                              assert(_newPrevStakeLimit <= uint96(-1));
                              assert(_data.prevStakeBlockNumber != 0);
                              _data.prevStakeLimit = uint96(_newPrevStakeLimit);
                              _data.prevStakeBlockNumber = uint32(block.number);
                              return _data;
                          }
                          /**
                          * @notice set stake limit pause state (on or off)
                          * @dev input `_data` param is mutated and the func returns effectively the same pointer
                          * @param _data stake limit state struct
                          * @param _isPaused pause state flag
                          */
                          function setStakeLimitPauseState(
                              StakeLimitState.Data memory _data,
                              bool _isPaused
                          ) internal view returns (StakeLimitState.Data memory) {
                              _data.prevStakeBlockNumber = uint32(_isPaused ? 0 : block.number);
                              return _data;
                          }
                      }
                      /*
                       * 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);
                      }
                      /*
                       * 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;
                          }
                      }
                      // 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();
                          }
                      }