ETH Price: $2,065.64 (+3.14%)

Transaction Decoder

Block:
23875551 at Nov-25-2025 11:35:35 AM +UTC
Transaction Fee:
0.000050301663551578 ETH $0.10
Gas Used:
561,478 Gas / 0.089587951 Gwei

Emitted Events:

365 GnosisSafeProxy.0x3d0ce9bfc3ed7d6862dbb28b2dea94561fe714a1b4d019aa8af39730d1ad7c3d( 0x3d0ce9bfc3ed7d6862dbb28b2dea94561fe714a1b4d019aa8af39730d1ad7c3d, 0x0000000000000000000000004bab2cb2ed6ee2d564ba5398cab4161d95e58f1b, 00000000000000000000000000000000000000000000000000019945ca262000 )
366 WETH9.Deposit( dst=0x3d90f66B534Dd8482b181e24655A9e8265316BE9, wad=149550000000000000 )
367 WETH9.Transfer( src=0x3d90f66B534Dd8482b181e24655A9e8265316BE9, dst=0x5DC24C79f898C358c5A52013aB58fe7DC592f3e4, wad=149550000000000000 )
368 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000e0554a476a092703abdb3ef35c80e0d76d32939f, 0x00000000000000000000000081fe240438f0631da32aaf5aba35f8960d2e78c9, 0000000000000000000000000000000000000000000000000000000019c81521 )
369 WETH9.Transfer( src=0x5DC24C79f898C358c5A52013aB58fe7DC592f3e4, dst=0xE0554a476A092703abdB3Ef35c80e0D76d32939F, wad=149550000000000000 )
370 0xe0554a476a092703abdb3ef35c80e0d76d32939f.0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67( 0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67, 0x0000000000000000000000005dc24c79f898c358c5a52013ab58fe7dc592f3e4, 0x00000000000000000000000081fe240438f0631da32aaf5aba35f8960d2e78c9, ffffffffffffffffffffffffffffffffffffffffffffffffffffffffe637eadf, 00000000000000000000000000000000000000000000000002134eeec228e000, 00000000000000000000000000000000000048a1dd19b9694e160c1d5943bfe1, 00000000000000000000000000000000000000000000000001e4c9bf1cdbdba2, 000000000000000000000000000000000000000000000000000000000003000d )
371 FiatTokenProxy.0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925( 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, 0x00000000000000000000000081fe240438f0631da32aaf5aba35f8960d2e78c9, 0x0000000000000000000000004f493b7de8aac7d55f71853688b1f7c8f0243c85, 0000000000000000000000000000000000000000000000000000000019c81521 )
372 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x00000000000000000000000081fe240438f0631da32aaf5aba35f8960d2e78c9, 0x0000000000000000000000004f493b7de8aac7d55f71853688b1f7c8f0243c85, 0000000000000000000000000000000000000000000000000000000019c81521 )
373 TetherToken.Transfer( from=CurveStableSwapNG, to=0x4Bab2Cb2Ed6Ee2d564Ba5398CAb4161d95E58f1b, value=432607667 )
374 CurveStableSwapNG.TokenExchange( buyer=0x81fe240438f0631da32aaf5aba35f8960d2e78c9, sold_id=0, tokens_sold=432543009, bought_id=1, tokens_bought=432607667 )
375 0x3d90f66b534dd8482b181e24655a9e8265316be9.0xe5b9f85c5caca875a8b78e5b2d88de86d7793cbff3d81ea4ecbec4c2b9ad7beb( 0xe5b9f85c5caca875a8b78e5b2d88de86d7793cbff3d81ea4ecbec4c2b9ad7beb, 0000000000000000000000000000000000000000000000003d35ee53236858cd, 000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, 000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec7, 00000000000000000000000069ab0d28e8a052da572a733645877f4cb6dfb333, 00000000000000000000000000000000000000000000000002134eeec228e000, 0000000000000000000000000000000000000000000000000000000019c911b3 )
376 TetherToken.Transfer( from=0x4Bab2Cb2Ed6Ee2d564Ba5398CAb4161d95E58f1b, to=[Receiver] 0x2fd66c64f61e793f6c6b20c7a32c45ed2df0a49f, value=432607667 )
377 0x4bab2cb2ed6ee2d564ba5398cab4161d95e58f1b.0x0751c3ad6c5272a7056d3872b521989518c655bbd49e2af71a26a26523927f84( 0x0751c3ad6c5272a7056d3872b521989518c655bbd49e2af71a26a26523927f84, 0000000000000000000000000000000000000000000000000000000000000001, 0000000000000000000000000000000000000000000000000000000000000000, 000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec7, 0000000000000000000000002fd66c64f61e793f6c6b20c7a32c45ed2df0a49f, 0000000000000000000000000000000000000000000000000214e8348c4f0000, 0000000000000000000000000000000000000000000000000000000019c911b3, 0000000000000000000000000000000000000000000000000000000019c897b6, 0000000000000000000000000000000000000000000000000000000019869631, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 00000000000000000000000033b99ccbc84e8a87e10ec86386a7eb5ad434fb7e, 00000000000000000000000000000000000000000000000000019945ca262000, 000000000000000000000000000000008d13a3a28a274cae97ea3c22b860eabe )

Account State Difference:

  Address   Before After State Difference Code
0x2FD66C64...d2dF0a49f
0.357810617575523087 Eth
Nonce: 5
0.207810617575523087 Eth
Nonce: 6
0.15From: 0 To: 22892027246769930685496490690840656788921382075819606463
0x33b99CcB...Ad434fB7E 36.721408473578780436 Eth36.721858473578780436 Eth0.00045
0x380fF867...24a8e5e25
(Titan Builder)
17.809145775216364782 Eth17.809145775300586482 Eth0.0000000000842217
0x4f493B7d...8F0243C85
0x69Ab0d28...Cb6dfb333
1.394514496868193154 Eth
Nonce: 10872
1.394464195204641576 Eth
Nonce: 10873
0.000050301663551578
0xA0b86991...E3606eB48
0xC02aaA39...83C756Cc2 2,642,680.101921187997077552 Eth2,642,680.251471187997077552 Eth0.14955
0xdAC17F95...13D831ec7
0xE0554a47...76d32939F
(Uniswap V3: USDC 4)

Execution Trace

0x2fd66c64f61e793f6c6b20c7a32c45ed2df0a49f.9265bb9d( )
  • 0x380ff86716cf5911b1d770ed53b74e524a8e5e25.0db39b93( )
    • Null: 0x000...001.349507ad( )
    • Null: 0x000...001.349507ad( )
    • ETH 0.15 Bitget: Swap 3.5742f567( )
      • ETH 0.15 0x4bab2cb2ed6ee2d564ba5398cab4161d95e58f1b.0eba4ffc( )
        • 0x4515b64147b8eff871929c90795ae9ecb542f162.3659871e( )
        • ETH 0.15 0xe270d1858d85d3f05f058028dcc175fc0f7feab4.0eba4ffc( )
          • 0x4515b64147b8eff871929c90795ae9ecb542f162.f090fa8d( )
          • 0x4515b64147b8eff871929c90795ae9ecb542f162.af2d9d81( )
          • TetherToken.balanceOf( who=0x2FD66C64F61E793F6C6b20C7A32C45Ed2dF0a49f ) => ( 0 )
          • 0xfbd46de044cf34dfd7386c6915cce74ef186c23e.3e50c31c( )
          • TetherToken.balanceOf( who=0x4Bab2Cb2Ed6Ee2d564Ba5398CAb4161d95E58f1b ) => ( 5200 )
          • ETH 0.00045 GnosisSafeProxy.CALL( )
            • ETH 0.00045 GnosisSafe.DELEGATECALL( )
            • ETH 0.14955 0x3d90f66b534dd8482b181e24655a9e8265316be9.47ee97ff( )
              • ETH 0.14955 0xe98333230360473ace143c9531c00c68a9aded64.47ee97ff( )
                • TetherToken.balanceOf( who=0x4Bab2Cb2Ed6Ee2d564Ba5398CAb4161d95E58f1b ) => ( 5200 )
                • ETH 0.14955 WETH9.CALL( )
                • WETH9.transfer( dst=0x5DC24C79f898C358c5A52013aB58fe7DC592f3e4, wad=149550000000000000 ) => ( True )
                • 0x5dc24c79f898c358c5a52013ab58fe7dc592f3e4.6f7929f2( )
                • FiatTokenProxy.70a08231( )
                • 0x81fe240438f0631da32aaf5aba35f8960d2e78c9.30e6ae31( )
                • TetherToken.balanceOf( who=0x3d90f66B534Dd8482b181e24655A9e8265316BE9 ) => ( 0 )
                • TetherToken.balanceOf( who=0x4Bab2Cb2Ed6Ee2d564Ba5398CAb4161d95E58f1b ) => ( 432612867 )
                • TetherToken.balanceOf( who=0x4Bab2Cb2Ed6Ee2d564Ba5398CAb4161d95E58f1b ) => ( 432612867 )
                • TetherToken.transfer( _to=0x2FD66C64F61E793F6C6b20C7A32C45Ed2dF0a49f, _value=432607667 )
                • TetherToken.balanceOf( who=0x2FD66C64F61E793F6C6b20C7A32C45Ed2dF0a49f ) => ( 432607667 )
                  File 1 of 6: GnosisSafeProxy
                  // SPDX-License-Identifier: LGPL-3.0-only
                  pragma solidity >=0.7.0 <0.9.0;
                  
                  /// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
                  /// @author Richard Meissner - <richard@gnosis.io>
                  interface IProxy {
                      function masterCopy() external view returns (address);
                  }
                  
                  /// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
                  /// @author Stefan George - <stefan@gnosis.io>
                  /// @author Richard Meissner - <richard@gnosis.io>
                  contract GnosisSafeProxy {
                      // singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
                      // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
                      address internal singleton;
                  
                      /// @dev Constructor function sets address of singleton contract.
                      /// @param _singleton Singleton address.
                      constructor(address _singleton) {
                          require(_singleton != address(0), "Invalid singleton address provided");
                          singleton = _singleton;
                      }
                  
                      /// @dev Fallback function forwards all transactions and returns all received return data.
                      fallback() external payable {
                          // solhint-disable-next-line no-inline-assembly
                          assembly {
                              let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
                              // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
                              if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
                                  mstore(0, _singleton)
                                  return(0, 0x20)
                              }
                              calldatacopy(0, 0, calldatasize())
                              let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
                              returndatacopy(0, 0, returndatasize())
                              if eq(success, 0) {
                                  revert(0, returndatasize())
                              }
                              return(0, returndatasize())
                          }
                      }
                  }
                  
                  /// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
                  /// @author Stefan George - <stefan@gnosis.pm>
                  contract GnosisSafeProxyFactory {
                      event ProxyCreation(GnosisSafeProxy proxy, address singleton);
                  
                      /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
                      /// @param singleton Address of singleton contract.
                      /// @param data Payload for message call sent to new proxy contract.
                      function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
                          proxy = new GnosisSafeProxy(singleton);
                          if (data.length > 0)
                              // solhint-disable-next-line no-inline-assembly
                              assembly {
                                  if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
                                      revert(0, 0)
                                  }
                              }
                          emit ProxyCreation(proxy, singleton);
                      }
                  
                      /// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
                      function proxyRuntimeCode() public pure returns (bytes memory) {
                          return type(GnosisSafeProxy).runtimeCode;
                      }
                  
                      /// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
                      function proxyCreationCode() public pure returns (bytes memory) {
                          return type(GnosisSafeProxy).creationCode;
                      }
                  
                      /// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
                      ///      This method is only meant as an utility to be called from other methods
                      /// @param _singleton Address of singleton contract.
                      /// @param initializer Payload for message call sent to new proxy contract.
                      /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                      function deployProxyWithNonce(
                          address _singleton,
                          bytes memory initializer,
                          uint256 saltNonce
                      ) internal returns (GnosisSafeProxy proxy) {
                          // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
                          bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
                          bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
                          // solhint-disable-next-line no-inline-assembly
                          assembly {
                              proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
                          }
                          require(address(proxy) != address(0), "Create2 call failed");
                      }
                  
                      /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
                      /// @param _singleton Address of singleton contract.
                      /// @param initializer Payload for message call sent to new proxy contract.
                      /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                      function createProxyWithNonce(
                          address _singleton,
                          bytes memory initializer,
                          uint256 saltNonce
                      ) public returns (GnosisSafeProxy proxy) {
                          proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
                          if (initializer.length > 0)
                              // solhint-disable-next-line no-inline-assembly
                              assembly {
                                  if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
                                      revert(0, 0)
                                  }
                              }
                          emit ProxyCreation(proxy, _singleton);
                      }
                  
                      /// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
                      /// @param _singleton Address of singleton contract.
                      /// @param initializer Payload for message call sent to new proxy contract.
                      /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                      /// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
                      function createProxyWithCallback(
                          address _singleton,
                          bytes memory initializer,
                          uint256 saltNonce,
                          IProxyCreationCallback callback
                      ) public returns (GnosisSafeProxy proxy) {
                          uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
                          proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
                          if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
                      }
                  
                      /// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
                      ///      This method is only meant for address calculation purpose when you use an initializer that would revert,
                      ///      therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
                      /// @param _singleton Address of singleton contract.
                      /// @param initializer Payload for message call sent to new proxy contract.
                      /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                      function calculateCreateProxyWithNonceAddress(
                          address _singleton,
                          bytes calldata initializer,
                          uint256 saltNonce
                      ) external returns (GnosisSafeProxy proxy) {
                          proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
                          revert(string(abi.encodePacked(proxy)));
                      }
                  }
                  
                  interface IProxyCreationCallback {
                      function proxyCreated(
                          GnosisSafeProxy proxy,
                          address _singleton,
                          bytes calldata initializer,
                          uint256 saltNonce
                      ) external;
                  }

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

                  File 3 of 6: 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 4 of 6: CurveStableSwapNG
                  # pragma version 0.3.10
                  # pragma optimize codesize
                  # pragma evm-version shanghai
                  """
                  @title CurveStableSwapNG
                  @author Curve.Fi
                  @license Copyright (c) Curve.Fi, 2020-2023 - all rights reserved
                  @notice Stableswap implementation for up to 8 coins with no rehypothecation,
                          i.e. the AMM does not deposit tokens into other contracts. The Pool contract also
                          records exponential moving averages for coins relative to coin 0.
                  @dev Asset Types:
                          0. Standard ERC20 token with no additional features.
                                            Note: Users are advised to do careful due-diligence on
                                                  ERC20 tokens that they interact with, as this
                                                  contract cannot differentiate between harmless and
                                                  malicious ERC20 tokens.
                          1. Oracle - token with rate oracle (e.g. wstETH)
                                      Note: Oracles may be controlled externally by an EOA. Users
                                            are advised to proceed with caution.
                          2. Rebasing - token with rebase (e.g. stETH).
                                        Note: Users and Integrators are advised to understand how
                                              the AMM contract works with rebasing balances.
                          3. ERC4626 - token with convertToAssets method (e.g. sDAI).
                                       Note: Some ERC4626 implementations may be susceptible to
                                             Donation/Inflation attacks. Users are advised to
                                             proceed with caution.
                          NOTE: Pool Cannot support tokens with multiple asset types: e.g. ERC4626
                                with fees are not supported.
                       Supports:
                          1. ERC20 support for return True/revert, return True/False, return None
                          2. ERC20 tokens can have arbitrary decimals (<=18).
                          3. ERC20 tokens that rebase (either positive or fee on transfer)
                          4. ERC20 tokens that have a rate oracle (e.g. wstETH, cbETH, sDAI, etc.)
                             Note: Oracle precision _must_ be 10**18.
                          5. ERC4626 tokens with arbitrary precision (<=18) of Vault token and underlying
                             asset.
                       Additional features include:
                          1. Adds price oracles based on AMM State Price (and _not_ last traded price).
                          2. Adds TVL oracle based on D.
                          3. `exchange_received`: swaps that expect an ERC20 transfer to have occurred
                             prior to executing the swap.
                             Note: a. If pool contains rebasing tokens and one of the `asset_types` is 2 (Rebasing)
                                      then calling `exchange_received` will REVERT.
                                   b. If pool contains rebasing token and `asset_types` does not contain 2 (Rebasing)
                                      then this is an incorrect implementation and rebases can be
                                      stolen.
                          4. Adds `get_dx`: Similar to `get_dy` which returns an expected output
                             of coin[j] for given `dx` amount of coin[i], `get_dx` returns expected
                             input of coin[i] for an output amount of coin[j].
                          5. Fees are dynamic: AMM will charge a higher fee if pool depegs. This can cause very
                                               slight discrepancies between calculated fees and realised fees.
                  """
                  
                  from vyper.interfaces import ERC20
                  from vyper.interfaces import ERC20Detailed
                  from vyper.interfaces import ERC4626
                  
                  implements: ERC20
                  
                  # ------------------------------- Interfaces ---------------------------------
                  
                  interface Factory:
                      def fee_receiver() -> address: view
                      def admin() -> address: view
                      def views_implementation() -> address: view
                  
                  interface ERC1271:
                      def isValidSignature(_hash: bytes32, _signature: Bytes[65]) -> bytes32: view
                  
                  interface StableSwapViews:
                      def get_dx(i: int128, j: int128, dy: uint256, pool: address) -> uint256: view
                      def get_dy(i: int128, j: int128, dx: uint256, pool: address) -> uint256: view
                      def dynamic_fee(i: int128, j: int128, pool: address) -> uint256: view
                      def calc_token_amount(
                          _amounts: DynArray[uint256, MAX_COINS],
                          _is_deposit: bool,
                          _pool: address
                      ) -> uint256: view
                  
                  # --------------------------------- Events -----------------------------------
                  
                  event Transfer:
                      sender: indexed(address)
                      receiver: indexed(address)
                      value: uint256
                  
                  event Approval:
                      owner: indexed(address)
                      spender: indexed(address)
                      value: uint256
                  
                  event TokenExchange:
                      buyer: indexed(address)
                      sold_id: int128
                      tokens_sold: uint256
                      bought_id: int128
                      tokens_bought: uint256
                  
                  event TokenExchangeUnderlying:
                      buyer: indexed(address)
                      sold_id: int128
                      tokens_sold: uint256
                      bought_id: int128
                      tokens_bought: uint256
                  
                  event AddLiquidity:
                      provider: indexed(address)
                      token_amounts: DynArray[uint256, MAX_COINS]
                      fees: DynArray[uint256, MAX_COINS]
                      invariant: uint256
                      token_supply: uint256
                  
                  event RemoveLiquidity:
                      provider: indexed(address)
                      token_amounts: DynArray[uint256, MAX_COINS]
                      fees: DynArray[uint256, MAX_COINS]
                      token_supply: uint256
                  
                  event RemoveLiquidityOne:
                      provider: indexed(address)
                      token_id: int128
                      token_amount: uint256
                      coin_amount: uint256
                      token_supply: uint256
                  
                  event RemoveLiquidityImbalance:
                      provider: indexed(address)
                      token_amounts: DynArray[uint256, MAX_COINS]
                      fees: DynArray[uint256, MAX_COINS]
                      invariant: uint256
                      token_supply: uint256
                  
                  event RampA:
                      old_A: uint256
                      new_A: uint256
                      initial_time: uint256
                      future_time: uint256
                  
                  event StopRampA:
                      A: uint256
                      t: uint256
                  
                  event ApplyNewFee:
                      fee: uint256
                      offpeg_fee_multiplier: uint256
                  
                  event SetNewMATime:
                      ma_exp_time: uint256
                      D_ma_time: uint256
                  
                  
                  MAX_COINS: constant(uint256) = 8  # max coins is 8 in the factory
                  MAX_COINS_128: constant(int128) = 8
                  
                  # ---------------------------- Pool Variables --------------------------------
                  
                  N_COINS: public(immutable(uint256))
                  N_COINS_128: immutable(int128)
                  PRECISION: constant(uint256) = 10 ** 18
                  
                  factory: immutable(Factory)
                  coins: public(immutable(DynArray[address, MAX_COINS]))
                  asset_types: immutable(DynArray[uint8, MAX_COINS])
                  pool_contains_rebasing_tokens: immutable(bool)
                  stored_balances: DynArray[uint256, MAX_COINS]
                  
                  # Fee specific vars
                  FEE_DENOMINATOR: constant(uint256) = 10 ** 10
                  fee: public(uint256)  # fee * 1e10
                  offpeg_fee_multiplier: public(uint256)  # * 1e10
                  admin_fee: public(constant(uint256)) = 5000000000
                  MAX_FEE: constant(uint256) = 5 * 10 ** 9
                  
                  # ---------------------- Pool Amplification Parameters -----------------------
                  
                  A_PRECISION: constant(uint256) = 100
                  MAX_A: constant(uint256) = 10 ** 6
                  MAX_A_CHANGE: constant(uint256) = 10
                  
                  initial_A: public(uint256)
                  future_A: public(uint256)
                  initial_A_time: public(uint256)
                  future_A_time: public(uint256)
                  
                  # ---------------------------- Admin Variables -------------------------------
                  
                  MIN_RAMP_TIME: constant(uint256) = 86400
                  admin_balances: public(DynArray[uint256, MAX_COINS])
                  
                  # ----------------------- Oracle Specific vars -------------------------------
                  
                  rate_multipliers: immutable(DynArray[uint256, MAX_COINS])
                  # [bytes4 method_id][bytes8 <empty>][bytes20 oracle]
                  rate_oracles: immutable(DynArray[uint256, MAX_COINS])
                  
                  # For ERC4626 tokens, we need:
                  call_amount: immutable(DynArray[uint256, MAX_COINS])
                  scale_factor: immutable(DynArray[uint256, MAX_COINS])
                  
                  last_prices_packed: DynArray[uint256, MAX_COINS]  #  packing: last_price, ma_price
                  last_D_packed: uint256                            #  packing: last_D, ma_D
                  ma_exp_time: public(uint256)
                  D_ma_time: public(uint256)
                  ma_last_time: public(uint256)                     # packing: ma_last_time_p, ma_last_time_D
                  # ma_last_time has a distinction for p and D because p is _not_ updated if
                  # users remove_liquidity, but D is.
                  
                  # shift(2**32 - 1, 224)
                  ORACLE_BIT_MASK: constant(uint256) = (2**32 - 1) * 256**28
                  
                  # --------------------------- ERC20 Specific Vars ----------------------------
                  
                  name: public(immutable(String[64]))
                  symbol: public(immutable(String[32]))
                  decimals: public(constant(uint8)) = 18
                  version: public(constant(String[8])) = "v7.0.0"
                  
                  balanceOf: public(HashMap[address, uint256])
                  allowance: public(HashMap[address, HashMap[address, uint256]])
                  total_supply: uint256
                  nonces: public(HashMap[address, uint256])
                  
                  # keccak256("isValidSignature(bytes32,bytes)")[:4] << 224
                  ERC1271_MAGIC_VAL: constant(bytes32) = 0x1626ba7e00000000000000000000000000000000000000000000000000000000
                  EIP712_TYPEHASH: constant(bytes32) = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)")
                  EIP2612_TYPEHASH: constant(bytes32) = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
                  
                  VERSION_HASH: constant(bytes32) = keccak256(version)
                  NAME_HASH: immutable(bytes32)
                  CACHED_CHAIN_ID: immutable(uint256)
                  salt: public(immutable(bytes32))
                  CACHED_DOMAIN_SEPARATOR: immutable(bytes32)
                  
                  
                  # ------------------------------ AMM Setup -----------------------------------
                  
                  
                  @external
                  def __init__(
                      _name: String[32],
                      _symbol: String[10],
                      _A: uint256,
                      _fee: uint256,
                      _offpeg_fee_multiplier: uint256,
                      _ma_exp_time: uint256,
                      _coins: DynArray[address, MAX_COINS],
                      _rate_multipliers: DynArray[uint256, MAX_COINS],
                      _asset_types: DynArray[uint8, MAX_COINS],
                      _method_ids: DynArray[bytes4, MAX_COINS],
                      _oracles: DynArray[address, MAX_COINS],
                  ):
                      """
                      @notice Initialize the pool contract
                      @param _name Name of the new plain pool.
                      @param _symbol Symbol for the new plain pool.
                      @param _A Amplification co-efficient - a lower value here means
                                less tolerance for imbalance within the pool's assets.
                                Suggested values include:
                                 * Uncollateralized algorithmic stablecoins: 5-10
                                 * Non-redeemable, collateralized assets: 100
                                 * Redeemable assets: 200-400
                      @param _fee Trade fee, given as an integer with 1e10 precision. The
                                  the maximum is 1% (100000000).
                                  50% of the fee is distributed to veCRV holders.
                      @param _offpeg_fee_multiplier A multiplier that determines how much to increase
                                                    Fees by when assets in the AMM depeg. Example value: 20000000000
                      @param _ma_exp_time Averaging window of oracle. Set as time_in_seconds / ln(2)
                                          Example: for 10 minute EMA, _ma_exp_time is 600 / ln(2) ~= 866
                      @param _coins List of addresses of the coins being used in the pool.
                      @param _rate_multipliers An array of: [10 ** (36 - _coins[n].decimals()), ... for n in range(N_COINS)]
                      @param _asset_types Array of uint8 representing tokens in pool
                      @param _method_ids Array of first four bytes of the Keccak-256 hash of the function signatures
                                         of the oracle addresses that gives rate oracles.
                                         Calculated as: keccak(text=event_signature.replace(" ", ""))[:4]
                      @param _oracles Array of rate oracle addresses.
                      """
                  
                      coins = _coins
                      asset_types = _asset_types
                      pool_contains_rebasing_tokens = 2 in asset_types
                      __n_coins: uint256 = len(_coins)
                      N_COINS = __n_coins
                      N_COINS_128 = convert(__n_coins, int128)
                  
                      rate_multipliers = _rate_multipliers
                  
                      factory = Factory(msg.sender)
                  
                      A: uint256 = unsafe_mul(_A, A_PRECISION)
                      self.initial_A = A
                      self.future_A = A
                      self.fee = _fee
                      self.offpeg_fee_multiplier = _offpeg_fee_multiplier
                  
                      assert _ma_exp_time != 0
                      self.ma_exp_time = _ma_exp_time
                      self.D_ma_time = 62324  # <--------- 12 hours default on contract start.
                      self.ma_last_time = self.pack_2(block.timestamp, block.timestamp)
                  
                      #  ------------------- initialize storage for DynArrays ------------------
                  
                      _call_amount: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS])
                      _scale_factor: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS])
                      _rate_oracles: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS])
                      for i in range(N_COINS_128, bound=MAX_COINS_128):
                  
                          if i < N_COINS_128 - 1:
                              self.last_prices_packed.append(self.pack_2(10**18, 10**18))
                  
                          _rate_oracles.append(convert(_method_ids[i], uint256) * 2**224 | convert(_oracles[i], uint256))
                          self.stored_balances.append(0)
                          self.admin_balances.append(0)
                  
                          if _asset_types[i] == 3:
                  
                              _call_amount.append(10**convert(ERC20Detailed(_coins[i]).decimals(), uint256))
                              _underlying_asset: address = ERC4626(_coins[i]).asset()
                              _scale_factor.append(10**(18 - convert(ERC20Detailed(_underlying_asset).decimals(), uint256)))
                  
                          else:
                  
                              _call_amount.append(0)
                              _scale_factor.append(0)
                  
                      call_amount = _call_amount
                      scale_factor = _scale_factor
                      rate_oracles = _rate_oracles
                  
                      # ----------------------------- ERC20 stuff ------------------------------
                  
                      name = _name
                      symbol = _symbol
                  
                      # EIP712 related params -----------------
                      NAME_HASH = keccak256(name)
                      salt = block.prevhash
                      CACHED_CHAIN_ID = chain.id
                      CACHED_DOMAIN_SEPARATOR = keccak256(
                          _abi_encode(
                              EIP712_TYPEHASH,
                              NAME_HASH,
                              VERSION_HASH,
                              chain.id,
                              self,
                              salt,
                          )
                      )
                  
                      # ------------------------ Fire a transfer event -------------------------
                  
                      log Transfer(empty(address), msg.sender, 0)
                  
                  
                  # ------------------ Token transfers in and out of the AMM -------------------
                  
                  
                  @internal
                  def _transfer_in(
                      coin_idx: int128,
                      dx: uint256,
                      sender: address,
                      expect_optimistic_transfer: bool,
                  ) -> uint256:
                      """
                      @notice Contains all logic to handle ERC20 token transfers.
                      @param coin_idx Index of the coin to transfer in.
                      @param dx amount of `_coin` to transfer into the pool.
                      @param sender address to transfer `_coin` from.
                      @param receiver address to transfer `_coin` to.
                      @param expect_optimistic_transfer True if contract expects an optimistic coin transfer
                      """
                      _dx: uint256 = ERC20(coins[coin_idx]).balanceOf(self)
                  
                      # ------------------------- Handle Transfers -----------------------------
                  
                      if expect_optimistic_transfer:
                  
                          _dx = _dx - self.stored_balances[coin_idx]
                          assert _dx >= dx
                  
                      else:
                  
                          assert dx > 0  # dev : do not transferFrom 0 tokens into the pool
                          assert ERC20(coins[coin_idx]).transferFrom(
                              sender, self, dx, default_return_value=True
                          )
                  
                          _dx = ERC20(coins[coin_idx]).balanceOf(self) - _dx
                  
                      # --------------------------- Store transferred in amount ---------------------------
                  
                      self.stored_balances[coin_idx] += _dx
                  
                      return _dx
                  
                  
                  @internal
                  def _transfer_out(_coin_idx: int128, _amount: uint256, receiver: address):
                      """
                      @notice Transfer a single token from the pool to receiver.
                      @dev This function is called by `remove_liquidity` and
                           `remove_liquidity_one_coin`, `_exchange`, `_withdraw_admin_fees` and
                           `remove_liquidity_imbalance` methods.
                      @param _coin_idx Index of the token to transfer out
                      @param _amount Amount of token to transfer out
                      @param receiver Address to send the tokens to
                      """
                      assert receiver != empty(address)  # dev: do not send tokens to zero_address
                  
                      if not pool_contains_rebasing_tokens:
                  
                          # we need not cache balanceOf pool before swap out
                          self.stored_balances[_coin_idx] -= _amount
                          assert ERC20(coins[_coin_idx]).transfer(
                              receiver, _amount, default_return_value=True
                          )
                  
                      else:
                  
                          # cache balances pre and post to account for fee on transfers etc.
                          coin_balance: uint256 = ERC20(coins[_coin_idx]).balanceOf(self)
                          assert ERC20(coins[_coin_idx]).transfer(
                              receiver, _amount, default_return_value=True
                          )
                          self.stored_balances[_coin_idx] = coin_balance - _amount
                  
                  
                  # -------------------------- AMM Special Methods -----------------------------
                  
                  
                  @view
                  @internal
                  def _stored_rates() -> DynArray[uint256, MAX_COINS]:
                      """
                      @notice Gets rate multipliers for each coin.
                      @dev If the coin has a rate oracle that has been properly initialised,
                           this method queries that rate by static-calling an external
                           contract.
                      """
                      rates: DynArray[uint256, MAX_COINS] = rate_multipliers
                  
                      for i in range(N_COINS_128, bound=MAX_COINS_128):
                  
                          if asset_types[i] == 1 and not rate_oracles[i] == 0:
                  
                              # NOTE: fetched_rate is assumed to be 10**18 precision
                              oracle_response: Bytes[32] = raw_call(
                                  convert(rate_oracles[i] % 2**160, address),
                                  _abi_encode(rate_oracles[i] & ORACLE_BIT_MASK),
                                  max_outsize=32,
                                  is_static_call=True,
                              )
                              assert len(oracle_response) == 32
                              fetched_rate: uint256 = convert(oracle_response, uint256)
                  
                              rates[i] = unsafe_div(rates[i] * fetched_rate, PRECISION)
                  
                          elif asset_types[i] == 3:  # ERC4626
                  
                              # fetched_rate: uint256 = ERC4626(coins[i]).convertToAssets(call_amount[i]) * scale_factor[i]
                              # here: call_amount has ERC4626 precision, but the returned value is scaled up to 18
                              # using scale_factor which is (18 - n) if underlying asset has n decimals.
                              rates[i] = unsafe_div(
                                  rates[i] * ERC4626(coins[i]).convertToAssets(call_amount[i]) * scale_factor[i],
                                  PRECISION
                              )  # 1e18 precision
                  
                      return rates
                  
                  
                  @view
                  @internal
                  def _balances() -> DynArray[uint256, MAX_COINS]:
                      """
                      @notice Calculates the pool's balances _excluding_ the admin's balances.
                      @dev If the pool contains rebasing tokens, this method ensures LPs keep all
                              rebases and admin only claims swap fees. This also means that, since
                              admin's balances are stored in an array and not inferred from read balances,
                              the fees in the rebasing token that the admin collects is immune to
                              slashing events.
                      """
                      result: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS])
                      balances_i: uint256 = 0
                  
                      for i in range(N_COINS_128, bound=MAX_COINS_128):
                  
                          if pool_contains_rebasing_tokens:
                              # Read balances by gulping to account for rebases
                              balances_i = ERC20(coins[i]).balanceOf(self) - self.admin_balances[i]
                          else:
                              # Use cached balances
                              balances_i = self.stored_balances[i] - self.admin_balances[i]
                  
                          result.append(balances_i)
                  
                      return result
                  
                  
                  # -------------------------- AMM Main Functions ------------------------------
                  
                  
                  @external
                  @nonreentrant('lock')
                  def exchange(
                      i: int128,
                      j: int128,
                      _dx: uint256,
                      _min_dy: uint256,
                      _receiver: address = msg.sender,
                  ) -> uint256:
                      """
                      @notice Perform an exchange between two coins
                      @dev Index values can be found via the `coins` public getter method
                      @param i Index value for the coin to send
                      @param j Index value of the coin to receive
                      @param _dx Amount of `i` being exchanged
                      @param _min_dy Minimum amount of `j` to receive
                      @param _receiver Address that receives `j`
                      @return Actual amount of `j` received
                      """
                      return self._exchange(
                          msg.sender,
                          i,
                          j,
                          _dx,
                          _min_dy,
                          _receiver,
                          False
                      )
                  
                  
                  @external
                  @nonreentrant('lock')
                  def exchange_received(
                      i: int128,
                      j: int128,
                      _dx: uint256,
                      _min_dy: uint256,
                      _receiver: address = msg.sender,
                  ) -> uint256:
                      """
                      @notice Perform an exchange between two coins without transferring token in
                      @dev The contract swaps tokens based on a change in balance of coin[i]. The
                           dx = ERC20(coin[i]).balanceOf(self) - self.stored_balances[i]. Users of
                           this method are dex aggregators, arbitrageurs, or other users who do not
                           wish to grant approvals to the contract: they would instead send tokens
                           directly to the contract and call `exchange_received`.
                           Note: This is disabled if pool contains rebasing tokens.
                      @param i Index value for the coin to send
                      @param j Index value of the coin to receive
                      @param _dx Amount of `i` being exchanged
                      @param _min_dy Minimum amount of `j` to receive
                      @param _receiver Address that receives `j`
                      @return Actual amount of `j` received
                      """
                      assert not pool_contains_rebasing_tokens  # dev: exchange_received not supported if pool contains rebasing tokens
                      return self._exchange(
                          msg.sender,
                          i,
                          j,
                          _dx,
                          _min_dy,
                          _receiver,
                          True,  # <--------------------------------------- swap optimistically.
                      )
                  
                  
                  @external
                  @nonreentrant('lock')
                  def add_liquidity(
                      _amounts: DynArray[uint256, MAX_COINS],
                      _min_mint_amount: uint256,
                      _receiver: address = msg.sender
                  ) -> uint256:
                      """
                      @notice Deposit coins into the pool
                      @param _amounts List of amounts of coins to deposit
                      @param _min_mint_amount Minimum amount of LP tokens to mint from the deposit
                      @param _receiver Address that owns the minted LP tokens
                      @return Amount of LP tokens received by depositing
                      """
                      assert _receiver != empty(address)  # dev: do not send LP tokens to zero_address
                  
                      amp: uint256 = self._A()
                      old_balances: DynArray[uint256, MAX_COINS] = self._balances()
                      rates: DynArray[uint256, MAX_COINS] = self._stored_rates()
                  
                      # Initial invariant
                      D0: uint256 = self.get_D_mem(rates, old_balances, amp)
                  
                      total_supply: uint256 = self.total_supply
                      new_balances: DynArray[uint256, MAX_COINS] = old_balances
                  
                      # -------------------------- Do Transfers In -----------------------------
                  
                      for i in range(N_COINS_128, bound=MAX_COINS_128):
                  
                          if _amounts[i] > 0:
                  
                              new_balances[i] += self._transfer_in(
                                  i,
                                  _amounts[i],
                                  msg.sender,
                                  False,  # expect_optimistic_transfer
                              )
                  
                          else:
                  
                              assert total_supply != 0  # dev: initial deposit requires all coins
                  
                      # ------------------------------------------------------------------------
                  
                      # Invariant after change
                      D1: uint256 = self.get_D_mem(rates, new_balances, amp)
                      assert D1 > D0
                  
                      # We need to recalculate the invariant accounting for fees
                      # to calculate fair user's share
                      fees: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS])
                      mint_amount: uint256 = 0
                  
                      if total_supply > 0:
                  
                          ideal_balance: uint256 = 0
                          difference: uint256 = 0
                          new_balance: uint256 = 0
                  
                          ys: uint256 = unsafe_div(D0 + D1, N_COINS)
                          xs: uint256 = 0
                          _dynamic_fee_i: uint256 = 0
                  
                          # Only account for fees if we are not the first to deposit
                          base_fee: uint256 = unsafe_div(
                              unsafe_mul(self.fee, N_COINS),
                              unsafe_mul(4, unsafe_sub(N_COINS, 1))
                          )
                  
                          for i in range(N_COINS_128, bound=MAX_COINS_128):
                  
                              ideal_balance = D1 * old_balances[i] / D0
                              difference = 0
                              new_balance = new_balances[i]
                  
                              if ideal_balance > new_balance:
                                  difference = unsafe_sub(ideal_balance, new_balance)
                              else:
                                  difference = unsafe_sub(new_balance, ideal_balance)
                  
                              # fee[i] = _dynamic_fee(i, j) * difference / FEE_DENOMINATOR
                              xs = unsafe_div(rates[i] * (old_balances[i] + new_balance), PRECISION)
                              _dynamic_fee_i = self._dynamic_fee(xs, ys, base_fee)
                              fees.append(unsafe_div(_dynamic_fee_i * difference, FEE_DENOMINATOR))
                              self.admin_balances[i] += unsafe_div(fees[i] * admin_fee, FEE_DENOMINATOR)
                              new_balances[i] -= fees[i]
                  
                          xp: DynArray[uint256, MAX_COINS] = self._xp_mem(rates, new_balances)
                          D1 = self.get_D(xp, amp)  # <--------------- Reuse D1 for new D value.
                          mint_amount = unsafe_div(total_supply * (D1 - D0), D0)
                          self.upkeep_oracles(xp, amp, D1)
                  
                      else:
                  
                          mint_amount = D1  # Take the dust if there was any
                  
                          # (re)instantiate D oracle if totalSupply is zero.
                          self.last_D_packed = self.pack_2(D1, D1)
                  
                          # Update D ma time:
                          ma_last_time_unpacked: uint256[2] = self.unpack_2(self.ma_last_time)
                          if ma_last_time_unpacked[1] < block.timestamp:
                              ma_last_time_unpacked[1] = block.timestamp
                              self.ma_last_time = self.pack_2(ma_last_time_unpacked[0], ma_last_time_unpacked[1])
                  
                      assert mint_amount >= _min_mint_amount, "Slippage screwed you"
                  
                      # Mint pool tokens
                      total_supply += mint_amount
                      self.balanceOf[_receiver] += mint_amount
                      self.total_supply = total_supply
                      log Transfer(empty(address), _receiver, mint_amount)
                  
                      log AddLiquidity(msg.sender, _amounts, fees, D1, total_supply)
                  
                      return mint_amount
                  
                  
                  @external
                  @nonreentrant('lock')
                  def remove_liquidity_one_coin(
                      _burn_amount: uint256,
                      i: int128,
                      _min_received: uint256,
                      _receiver: address = msg.sender,
                  ) -> uint256:
                      """
                      @notice Withdraw a single coin from the pool
                      @param _burn_amount Amount of LP tokens to burn in the withdrawal
                      @param i Index value of the coin to withdraw
                      @param _min_received Minimum amount of coin to receive
                      @param _receiver Address that receives the withdrawn coins
                      @return Amount of coin received
                      """
                      assert _burn_amount > 0  # dev: do not remove 0 LP tokens
                      dy: uint256 = 0
                      fee: uint256 = 0
                      xp: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS])
                      amp: uint256 = empty(uint256)
                      D: uint256 = empty(uint256)
                  
                      dy, fee, xp, amp, D = self._calc_withdraw_one_coin(_burn_amount, i)
                      assert dy >= _min_received, "Not enough coins removed"
                  
                      self.admin_balances[i] += unsafe_div(fee * admin_fee, FEE_DENOMINATOR)
                  
                      self._burnFrom(msg.sender, _burn_amount)
                  
                      self._transfer_out(i, dy, _receiver)
                  
                      log RemoveLiquidityOne(msg.sender, i, _burn_amount, dy, self.total_supply)
                  
                      self.upkeep_oracles(xp, amp, D)
                  
                      return dy
                  
                  
                  @external
                  @nonreentrant('lock')
                  def remove_liquidity_imbalance(
                      _amounts: DynArray[uint256, MAX_COINS],
                      _max_burn_amount: uint256,
                      _receiver: address = msg.sender
                  ) -> uint256:
                      """
                      @notice Withdraw coins from the pool in an imbalanced amount
                      @param _amounts List of amounts of underlying coins to withdraw
                      @param _max_burn_amount Maximum amount of LP token to burn in the withdrawal
                      @param _receiver Address that receives the withdrawn coins
                      @return Actual amount of the LP token burned in the withdrawal
                      """
                      amp: uint256 = self._A()
                      rates: DynArray[uint256, MAX_COINS] = self._stored_rates()
                      old_balances: DynArray[uint256, MAX_COINS] = self._balances()
                      D0: uint256 = self.get_D_mem(rates, old_balances, amp)
                      new_balances: DynArray[uint256, MAX_COINS] = old_balances
                  
                      for i in range(N_COINS_128, bound=MAX_COINS_128):
                  
                          if _amounts[i] != 0:
                              new_balances[i] -= _amounts[i]
                              self._transfer_out(i, _amounts[i], _receiver)
                  
                      D1: uint256 = self.get_D_mem(rates, new_balances, amp)
                      base_fee: uint256 = unsafe_div(
                          unsafe_mul(self.fee, N_COINS),
                          unsafe_mul(4, unsafe_sub(N_COINS, 1))
                      )
                      ys: uint256 = unsafe_div((D0 + D1), N_COINS)
                  
                      fees: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS])
                      dynamic_fee: uint256 = 0
                      xs: uint256 = 0
                      ideal_balance: uint256 = 0
                      difference: uint256 = 0
                      new_balance: uint256 = 0
                  
                      for i in range(N_COINS_128, bound=MAX_COINS_128):
                  
                          ideal_balance = D1 * old_balances[i] / D0
                          difference = 0
                          new_balance = new_balances[i]
                  
                          if ideal_balance > new_balance:
                              difference = unsafe_sub(ideal_balance, new_balance)
                          else:
                              difference = unsafe_sub(new_balance, ideal_balance)
                  
                          xs = unsafe_div(rates[i] * (old_balances[i] + new_balance), PRECISION)
                          dynamic_fee = self._dynamic_fee(xs, ys, base_fee)
                          fees.append(unsafe_div(dynamic_fee * difference, FEE_DENOMINATOR))
                  
                          self.admin_balances[i] += unsafe_div(fees[i] * admin_fee, FEE_DENOMINATOR)
                          new_balances[i] -= fees[i]
                  
                      D1 = self.get_D_mem(rates, new_balances, amp)  # dev: reuse D1 for new D.
                      self.upkeep_oracles(self._xp_mem(rates, new_balances), amp, D1)
                  
                      total_supply: uint256 = self.total_supply
                      burn_amount: uint256 = unsafe_div((D0 - D1) * total_supply, D0) + 1
                      assert burn_amount > 1  # dev: zero tokens burned
                      assert burn_amount <= _max_burn_amount, "Slippage screwed you"
                  
                      self._burnFrom(msg.sender, burn_amount)
                  
                      log RemoveLiquidityImbalance(
                          msg.sender,
                          _amounts,
                          fees,
                          D1,
                          total_supply - burn_amount
                      )
                  
                      return burn_amount
                  
                  
                  @external
                  @nonreentrant('lock')
                  def remove_liquidity(
                      _burn_amount: uint256,
                      _min_amounts: DynArray[uint256, MAX_COINS],
                      _receiver: address = msg.sender,
                      _claim_admin_fees: bool = True,
                  ) -> DynArray[uint256, MAX_COINS]:
                      """
                      @notice Withdraw coins from the pool
                      @dev Withdrawal amounts are based on current deposit ratios
                      @param _burn_amount Quantity of LP tokens to burn in the withdrawal
                      @param _min_amounts Minimum amounts of underlying coins to receive
                      @param _receiver Address that receives the withdrawn coins
                      @return List of amounts of coins that were withdrawn
                      """
                      total_supply: uint256 = self.total_supply
                      assert _burn_amount > 0  # dev: invalid burn amount
                      assert len(_min_amounts) == N_COINS  # dev: invalid array length for _min_amounts
                  
                      amounts: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS])
                      balances: DynArray[uint256, MAX_COINS] = self._balances()
                  
                      value: uint256 = 0
                      for i in range(N_COINS_128, bound=MAX_COINS_128):
                  
                          value = unsafe_div(balances[i] * _burn_amount, total_supply)
                          assert value >= _min_amounts[i], "Withdrawal resulted in fewer coins than expected"
                          amounts.append(value)
                          self._transfer_out(i, value, _receiver)
                  
                      self._burnFrom(msg.sender, _burn_amount)  # <---- Updates self.total_supply
                  
                      # --------------------------- Upkeep D_oracle ----------------------------
                  
                      ma_last_time_unpacked: uint256[2] = self.unpack_2(self.ma_last_time)
                      last_D_packed_current: uint256 = self.last_D_packed
                      old_D: uint256 = last_D_packed_current & (2**128 - 1)
                  
                      self.last_D_packed = self.pack_2(
                          old_D - unsafe_div(old_D * _burn_amount, total_supply),  # new_D = proportionally reduce D.
                          self._calc_moving_average(
                              last_D_packed_current,
                              self.D_ma_time,
                              ma_last_time_unpacked[1]
                          )
                      )
                  
                      if ma_last_time_unpacked[1] < block.timestamp:
                          ma_last_time_unpacked[1] = block.timestamp
                          self.ma_last_time = self.pack_2(ma_last_time_unpacked[0], ma_last_time_unpacked[1])
                  
                      # ------------------------------- Log event ------------------------------
                  
                      log RemoveLiquidity(
                          msg.sender,
                          amounts,
                          empty(DynArray[uint256, MAX_COINS]),
                          unsafe_sub(total_supply, _burn_amount)
                      )
                  
                      # ------- Withdraw admin fees if _claim_admin_fees is set to True --------
                      if _claim_admin_fees:
                          self._withdraw_admin_fees()
                  
                      return amounts
                  
                  
                  @external
                  @nonreentrant('lock')
                  def withdraw_admin_fees():
                      """
                      @notice Claim admin fees. Callable by anyone.
                      """
                      self._withdraw_admin_fees()
                  
                  
                  # ------------------------ AMM Internal Functions ----------------------------
                  
                  
                  @view
                  @internal
                  def _dynamic_fee(xpi: uint256, xpj: uint256, _fee: uint256) -> uint256:
                  
                      _offpeg_fee_multiplier: uint256 = self.offpeg_fee_multiplier
                      if _offpeg_fee_multiplier <= FEE_DENOMINATOR:
                          return _fee
                  
                      xps2: uint256 = (xpi + xpj) ** 2
                      return unsafe_div(
                          unsafe_mul(_offpeg_fee_multiplier, _fee),
                          unsafe_add(
                              unsafe_sub(_offpeg_fee_multiplier, FEE_DENOMINATOR) * 4 * xpi * xpj / xps2,
                              FEE_DENOMINATOR
                          )
                      )
                  
                  
                  @internal
                  def __exchange(
                      x: uint256,
                      _xp: DynArray[uint256, MAX_COINS],
                      rates: DynArray[uint256, MAX_COINS],
                      i: int128,
                      j: int128,
                  ) -> uint256:
                  
                      amp: uint256 = self._A()
                      D: uint256 = self.get_D(_xp, amp)
                      y: uint256 = self.get_y(i, j, x, _xp, amp, D)
                  
                      dy: uint256 = _xp[j] - y - 1  # -1 just in case there were some rounding errors
                      dy_fee: uint256 = unsafe_div(
                          dy * self._dynamic_fee(
                              unsafe_div(_xp[i] + x, 2), unsafe_div(_xp[j] + y, 2), self.fee
                          ),
                          FEE_DENOMINATOR
                      )
                  
                      # Convert all to real units
                      dy = (dy - dy_fee) * PRECISION / rates[j]
                  
                      self.admin_balances[j] += unsafe_div(
                          unsafe_div(dy_fee * admin_fee, FEE_DENOMINATOR) * PRECISION,
                          rates[j]
                      )
                  
                      # Calculate and store state prices:
                      xp: DynArray[uint256, MAX_COINS] = _xp
                      xp[i] = x
                      xp[j] = y
                      # D is not changed because we did not apply a fee
                      self.upkeep_oracles(xp, amp, D)
                  
                      return dy
                  
                  
                  @internal
                  def _exchange(
                      sender: address,
                      i: int128,
                      j: int128,
                      _dx: uint256,
                      _min_dy: uint256,
                      receiver: address,
                      expect_optimistic_transfer: bool
                  ) -> uint256:
                  
                      assert i != j  # dev: coin index out of range
                      assert _dx > 0  # dev: do not exchange 0 coins
                  
                      rates: DynArray[uint256, MAX_COINS] = self._stored_rates()
                      old_balances: DynArray[uint256, MAX_COINS] = self._balances()
                      xp: DynArray[uint256, MAX_COINS] = self._xp_mem(rates, old_balances)
                  
                      # --------------------------- Do Transfer in -----------------------------
                  
                      # `dx` is whatever the pool received after ERC20 transfer:
                      dx: uint256 = self._transfer_in(
                          i,
                          _dx,
                          sender,
                          expect_optimistic_transfer
                      )
                  
                      # ------------------------------- Exchange -------------------------------
                  
                      x: uint256 = xp[i] + unsafe_div(dx * rates[i], PRECISION)
                      dy: uint256 = self.__exchange(x, xp, rates, i, j)
                      assert dy >= _min_dy, "Exchange resulted in fewer coins than expected"
                  
                      # --------------------------- Do Transfer out ----------------------------
                  
                      self._transfer_out(j, dy, receiver)
                  
                      # ------------------------------------------------------------------------
                  
                      log TokenExchange(msg.sender, i, dx, j, dy)
                  
                      return dy
                  
                  
                  @internal
                  def _withdraw_admin_fees():
                      fee_receiver: address = factory.fee_receiver()
                      if fee_receiver == empty(address):
                          return  # Do nothing.
                  
                      admin_balances: DynArray[uint256, MAX_COINS] = self.admin_balances
                      for i in range(N_COINS_128, bound=MAX_COINS_128):
                  
                          if admin_balances[i] > 0:
                  
                              self._transfer_out(i, admin_balances[i], fee_receiver)
                              admin_balances[i] = 0
                  
                      self.admin_balances = admin_balances
                  
                  
                  # --------------------------- AMM Math Functions -----------------------------
                  
                  
                  @view
                  @internal
                  def get_y(
                      i: int128,
                      j: int128,
                      x: uint256,
                      xp: DynArray[uint256, MAX_COINS],
                      _amp: uint256,
                      _D: uint256
                  ) -> uint256:
                      """
                      Calculate x[j] if one makes x[i] = x
                  
                      Done by solving quadratic equation iteratively.
                      x_1**2 + x_1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)
                      x_1**2 + b*x_1 = c
                  
                      x_1 = (x_1**2 + c) / (2*x_1 + b)
                      """
                      # x in the input is converted to the same price/precision
                  
                      assert i != j       # dev: same coin
                      assert j >= 0       # dev: j below zero
                      assert j < N_COINS_128  # dev: j above N_COINS
                  
                      # should be unreachable, but good for safety
                      assert i >= 0
                      assert i < N_COINS_128
                  
                      amp: uint256 = _amp
                      D: uint256 = _D
                  
                      S_: uint256 = 0
                      _x: uint256 = 0
                      y_prev: uint256 = 0
                      c: uint256 = D
                      Ann: uint256 = amp * N_COINS
                  
                      for _i in range(MAX_COINS_128):
                  
                          if _i == N_COINS_128:
                              break
                  
                          if _i == i:
                              _x = x
                          elif _i != j:
                              _x = xp[_i]
                          else:
                              continue
                  
                          S_ += _x
                          c = c * D / (_x * N_COINS)
                  
                      c = c * D * A_PRECISION / (Ann * N_COINS)
                      b: uint256 = S_ + D * A_PRECISION / Ann  # - D
                      y: uint256 = D
                  
                      for _i in range(255):
                          y_prev = y
                          y = (y*y + c) / (2 * y + b - D)
                          # Equality with the precision of 1
                          if y > y_prev:
                              if y - y_prev <= 1:
                                  return y
                          else:
                              if y_prev - y <= 1:
                                  return y
                      raise
                  
                  
                  @pure
                  @internal
                  def get_D(_xp: DynArray[uint256, MAX_COINS], _amp: uint256) -> uint256:
                      """
                      D invariant calculation in non-overflowing integer operations
                      iteratively
                  
                      A * sum(x_i) * n**n + D = A * D * n**n + D**(n+1) / (n**n * prod(x_i))
                  
                      Converging solution:
                      D[j+1] = (A * n**n * sum(x_i) - D[j]**(n+1) / (n**n prod(x_i))) / (A * n**n - 1)
                      """
                      S: uint256 = 0
                      for x in _xp:
                          S += x
                      if S == 0:
                          return 0
                  
                      D: uint256 = S
                      Ann: uint256 = _amp * N_COINS
                  
                      for i in range(255):
                  
                          D_P: uint256 = D
                          for x in _xp:
                              D_P = D_P * D / x
                          D_P /= pow_mod256(N_COINS, N_COINS)
                          Dprev: uint256 = D
                  
                          # (Ann * S / A_PRECISION + D_P * N_COINS) * D / ((Ann - A_PRECISION) * D / A_PRECISION + (N_COINS + 1) * D_P)
                          D = (
                              (unsafe_div(Ann * S, A_PRECISION) + D_P * N_COINS) * D
                              /
                              (
                                  unsafe_div((Ann - A_PRECISION) * D, A_PRECISION) +
                                  unsafe_add(N_COINS, 1) * D_P
                              )
                          )
                  
                          # Equality with the precision of 1
                          if D > Dprev:
                              if D - Dprev <= 1:
                                  return D
                          else:
                              if Dprev - D <= 1:
                                  return D
                      # convergence typically occurs in 4 rounds or less, this should be unreachable!
                      # if it does happen the pool is borked and LPs can withdraw via `remove_liquidity`
                      raise
                  
                  
                  @pure
                  @internal
                  def get_y_D(
                      A: uint256,
                      i: int128,
                      xp: DynArray[uint256, MAX_COINS],
                      D: uint256
                  ) -> uint256:
                      """
                      Calculate x[i] if one reduces D from being calculated for xp to D
                  
                      Done by solving quadratic equation iteratively.
                      x_1**2 + x_1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)
                      x_1**2 + b*x_1 = c
                  
                      x_1 = (x_1**2 + c) / (2*x_1 + b)
                      """
                      # x in the input is converted to the same price/precision
                  
                      assert i >= 0  # dev: i below zero
                      assert i < N_COINS_128  # dev: i above N_COINS
                  
                      S_: uint256 = 0
                      _x: uint256 = 0
                      y_prev: uint256 = 0
                      c: uint256 = D
                      Ann: uint256 = A * N_COINS
                  
                      for _i in range(MAX_COINS_128):
                  
                          if _i == N_COINS_128:
                              break
                  
                          if _i != i:
                              _x = xp[_i]
                          else:
                              continue
                          S_ += _x
                          c = c * D / (_x * N_COINS)
                  
                      c = c * D * A_PRECISION / (Ann * N_COINS)
                      b: uint256 = S_ + D * A_PRECISION / Ann
                      y: uint256 = D
                  
                      for _i in range(255):
                          y_prev = y
                          y = (y*y + c) / (2 * y + b - D)
                          # Equality with the precision of 1
                          if y > y_prev:
                              if y - y_prev <= 1:
                                  return y
                          else:
                              if y_prev - y <= 1:
                                  return y
                      raise
                  
                  
                  @view
                  @internal
                  def _A() -> uint256:
                      """
                      Handle ramping A up or down
                      """
                      t1: uint256 = self.future_A_time
                      A1: uint256 = self.future_A
                  
                      if block.timestamp < t1:
                          A0: uint256 = self.initial_A
                          t0: uint256 = self.initial_A_time
                          # Expressions in uint256 cannot have negative numbers, thus "if"
                          if A1 > A0:
                              return A0 + unsafe_sub(A1, A0) * (block.timestamp - t0) / (t1 - t0)
                          else:
                              return A0 - unsafe_sub(A0, A1) * (block.timestamp - t0) / (t1 - t0)
                  
                      else:  # when t1 == 0 or block.timestamp >= t1
                          return A1
                  
                  
                  @pure
                  @internal
                  def _xp_mem(
                      _rates: DynArray[uint256, MAX_COINS],
                      _balances: DynArray[uint256, MAX_COINS]
                  ) -> DynArray[uint256, MAX_COINS]:
                  
                      result: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS])
                      for i in range(N_COINS_128, bound=MAX_COINS_128):
                          result.append(unsafe_div(_rates[i] * _balances[i], PRECISION))
                      return result
                  
                  
                  @view
                  @internal
                  def get_D_mem(
                      _rates: DynArray[uint256, MAX_COINS],
                      _balances: DynArray[uint256, MAX_COINS],
                      _amp: uint256
                  ) -> uint256:
                      xp: DynArray[uint256, MAX_COINS] = self._xp_mem(_rates, _balances)
                      return self.get_D(xp, _amp)
                  
                  
                  @view
                  @internal
                  def _calc_withdraw_one_coin(
                      _burn_amount: uint256,
                      i: int128
                  ) -> (
                      uint256,
                      uint256,
                      DynArray[uint256, MAX_COINS],
                      uint256,
                      uint256
                  ):
                      # First, need to calculate
                      # * Get current D
                      # * Solve Eqn against y_i for D - _token_amount
                      amp: uint256 = self._A()
                      rates: DynArray[uint256, MAX_COINS] = self._stored_rates()
                      xp: DynArray[uint256, MAX_COINS] = self._xp_mem(rates, self._balances())
                      D0: uint256 = self.get_D(xp, amp)
                  
                      total_supply: uint256 = self.total_supply
                      D1: uint256 = D0 - _burn_amount * D0 / total_supply
                      new_y: uint256 = self.get_y_D(amp, i, xp, D1)
                  
                      base_fee: uint256 = unsafe_div(
                          unsafe_mul(self.fee, N_COINS),
                          unsafe_mul(4, unsafe_sub(N_COINS, 1))
                      )
                      xp_reduced: DynArray[uint256, MAX_COINS] = xp
                      ys: uint256 = unsafe_div((D0 + D1), unsafe_mul(2, N_COINS))
                  
                      dx_expected: uint256 = 0
                      xp_j: uint256 = 0
                      xavg: uint256 = 0
                      dynamic_fee: uint256 = 0
                  
                      for j in range(MAX_COINS_128):
                  
                          if j == N_COINS_128:
                              break
                  
                          dx_expected = 0
                          xp_j = xp[j]
                  
                          if j == i:
                              dx_expected = xp_j * D1 / D0 - new_y
                              xavg = unsafe_div((xp_j + new_y), 2)
                          else:
                              dx_expected = xp_j - xp_j * D1 / D0
                              xavg = xp_j
                  
                          dynamic_fee = self._dynamic_fee(xavg, ys, base_fee)
                          xp_reduced[j] = xp_j - unsafe_div(dynamic_fee * dx_expected, FEE_DENOMINATOR)
                  
                      dy: uint256 = xp_reduced[i] - self.get_y_D(amp, i, xp_reduced, D1)
                      dy_0: uint256 = (xp[i] - new_y) * PRECISION / rates[i]  # w/o fees
                      dy = unsafe_div((dy - 1) * PRECISION, rates[i])  # Withdraw less to account for rounding errors
                  
                      # update xp with new_y for p calculations.
                      xp[i] = new_y
                  
                      return dy, dy_0 - dy, xp, amp, D1
                  
                  
                  # -------------------------- AMM Price Methods -------------------------------
                  
                  @pure
                  @internal
                  def pack_2(p1: uint256, p2: uint256) -> uint256:
                      assert p1 < 2**128
                      assert p2 < 2**128
                      return p1 | (p2 << 128)
                  
                  
                  @pure
                  @internal
                  def unpack_2(packed: uint256) -> uint256[2]:
                      return [packed & (2**128 - 1), packed >> 128]
                  
                  
                  @internal
                  @pure
                  def _get_p(
                      xp: DynArray[uint256, MAX_COINS],
                      amp: uint256,
                      D: uint256,
                  ) -> DynArray[uint256, MAX_COINS]:
                  
                      # dx_0 / dx_1 only, however can have any number of coins in pool
                      ANN: uint256 = unsafe_mul(amp, N_COINS)
                      Dr: uint256 = unsafe_div(D, pow_mod256(N_COINS, N_COINS))
                  
                      for i in range(N_COINS_128, bound=MAX_COINS_128):
                          Dr = Dr * D / xp[i]
                  
                      p: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS])
                      xp0_A: uint256 = unsafe_div(ANN * xp[0], A_PRECISION)
                  
                      for i in range(1, MAX_COINS):
                  
                          if i == N_COINS:
                              break
                  
                          p.append(10**18 * (xp0_A + unsafe_div(Dr * xp[0], xp[i])) / (xp0_A + Dr))
                  
                      return p
                  
                  
                  @internal
                  def upkeep_oracles(xp: DynArray[uint256, MAX_COINS], amp: uint256, D: uint256):
                      """
                      @notice Upkeeps price and D oracles.
                      """
                      ma_last_time_unpacked: uint256[2] = self.unpack_2(self.ma_last_time)
                      last_prices_packed_current: DynArray[uint256, MAX_COINS] = self.last_prices_packed
                      last_prices_packed_new: DynArray[uint256, MAX_COINS] = last_prices_packed_current
                  
                      spot_price: DynArray[uint256, MAX_COINS] = self._get_p(xp, amp, D)
                  
                      # -------------------------- Upkeep price oracle -------------------------
                  
                      for i in range(MAX_COINS):
                  
                          if i == N_COINS - 1:
                              break
                  
                          if spot_price[i] != 0:
                  
                              # Update packed prices -----------------
                              last_prices_packed_new[i] = self.pack_2(
                                  min(spot_price[i], 2 * 10**18),  # <----- Cap spot value by 2.
                                  self._calc_moving_average(
                                      last_prices_packed_current[i],
                                      self.ma_exp_time,
                                      ma_last_time_unpacked[0],  # index 0 is ma_last_time for prices
                                  )
                              )
                  
                      self.last_prices_packed = last_prices_packed_new
                  
                      # ---------------------------- Upkeep D oracle ---------------------------
                  
                      last_D_packed_current: uint256 = self.last_D_packed
                      self.last_D_packed = self.pack_2(
                          D,
                          self._calc_moving_average(
                              last_D_packed_current,
                              self.D_ma_time,
                              ma_last_time_unpacked[1],  # index 1 is ma_last_time for D
                          )
                      )
                  
                      # Housekeeping: Update ma_last_time for p and D oracles ------------------
                      for i in range(2):
                          if ma_last_time_unpacked[i] < block.timestamp:
                              ma_last_time_unpacked[i] = block.timestamp
                  
                      self.ma_last_time = self.pack_2(ma_last_time_unpacked[0], ma_last_time_unpacked[1])
                  
                  
                  @internal
                  @view
                  def _calc_moving_average(
                      packed_value: uint256,
                      averaging_window: uint256,
                      ma_last_time: uint256
                  ) -> uint256:
                  
                      last_spot_value: uint256 = packed_value & (2**128 - 1)
                      last_ema_value: uint256 = (packed_value >> 128)
                  
                      if ma_last_time < block.timestamp:  # calculate new_ema_value and return that.
                          alpha: uint256 = self.exp(
                              -convert(
                                  unsafe_div(unsafe_mul(unsafe_sub(block.timestamp, ma_last_time), 10**18), averaging_window), int256
                              )
                          )
                          return unsafe_div(last_spot_value * (10**18 - alpha) + last_ema_value * alpha, 10**18)
                  
                      return last_ema_value
                  
                  
                  @view
                  @external
                  def last_price(i: uint256) -> uint256:
                      return self.last_prices_packed[i] & (2**128 - 1)
                  
                  
                  @view
                  @external
                  def ema_price(i: uint256) -> uint256:
                      return (self.last_prices_packed[i] >> 128)
                  
                  
                  @external
                  @view
                  def get_p(i: uint256) -> uint256:
                      """
                      @notice Returns the AMM State price of token
                      @dev if i = 0, it will return the state price of coin[1].
                      @param i index of state price (0 for coin[1], 1 for coin[2], ...)
                      @return uint256 The state price quoted by the AMM for coin[i+1]
                      """
                      amp: uint256 = self._A()
                      xp: DynArray[uint256, MAX_COINS] = self._xp_mem(
                          self._stored_rates(), self._balances()
                      )
                      D: uint256 = self.get_D(xp, amp)
                      return self._get_p(xp, amp, D)[i]
                  
                  
                  @external
                  @view
                  @nonreentrant('lock')
                  def price_oracle(i: uint256) -> uint256:
                      return self._calc_moving_average(
                          self.last_prices_packed[i],
                          self.ma_exp_time,
                          self.ma_last_time & (2**128 - 1)
                      )
                  
                  
                  @external
                  @view
                  @nonreentrant('lock')
                  def D_oracle() -> uint256:
                      return self._calc_moving_average(
                          self.last_D_packed,
                          self.D_ma_time,
                          self.ma_last_time >> 128
                      )
                  
                  
                  # ----------------------------- Math Utils -----------------------------------
                  
                  
                  @internal
                  @pure
                  def exp(x: int256) -> uint256:
                      """
                      @dev Calculates the natural exponential function of a signed integer with
                           a precision of 1e18.
                      @notice Note that this function consumes about 810 gas units. The implementation
                              is inspired by Remco Bloemen's implementation under the MIT license here:
                              https://xn--2-umb.com/22/exp-ln.
                      @dev This implementation is derived from Snekmate, which is authored
                           by pcaversaccio (Snekmate), distributed under the AGPL-3.0 license.
                           https://github.com/pcaversaccio/snekmate
                      @param x The 32-byte variable.
                      @return int256 The 32-byte calculation result.
                      """
                      value: int256 = x
                  
                      # If the result is `< 0.5`, we return zero. This happens when we have the following:
                      # "x <= floor(log(0.5e18) * 1e18) ~ -42e18".
                      if (x <= -41446531673892822313):
                          return empty(uint256)
                  
                      # When the result is "> (2 ** 255 - 1) / 1e18" we cannot represent it as a signed integer.
                      # This happens when "x >= floor(log((2 ** 255 - 1) / 1e18) * 1e18) ~ 135".
                      assert x < 135305999368893231589, "wad_exp overflow"
                  
                      # `x` is now in the range "(-42, 136) * 1e18". Convert to "(-42, 136) * 2 ** 96" for higher
                      # intermediate precision and a binary base. This base conversion is a multiplication with
                      # "1e18 / 2 ** 96 = 5 ** 18 / 2 ** 78".
                      value = unsafe_div(x << 78, 5 ** 18)
                  
                      # Reduce the range of `x` to "(-½ ln 2, ½ ln 2) * 2 ** 96" by factoring out powers of two
                      # so that "exp(x) = exp(x') * 2 ** k", where `k` is a signer integer. Solving this gives
                      # "k = round(x / log(2))" and "x' = x - k * log(2)". Thus, `k` is in the range "[-61, 195]".
                      k: int256 = unsafe_add(unsafe_div(value << 96, 54916777467707473351141471128), 2 ** 95) >> 96
                      value = unsafe_sub(value, unsafe_mul(k, 54916777467707473351141471128))
                  
                      # Evaluate using a "(6, 7)"-term rational approximation. Since `p` is monic,
                      # we will multiply by a scaling factor later.
                      y: int256 = unsafe_add(unsafe_mul(unsafe_add(value, 1346386616545796478920950773328), value) >> 96, 57155421227552351082224309758442)
                      p: int256 = unsafe_add(unsafe_mul(unsafe_add(unsafe_mul(unsafe_sub(unsafe_add(y, value), 94201549194550492254356042504812), y) >> 96,\
                                             28719021644029726153956944680412240), value), 4385272521454847904659076985693276 << 96)
                  
                      # We leave `p` in the "2 ** 192" base so that we do not have to scale it up
                      # again for the division.
                      q: int256 = unsafe_add(unsafe_mul(unsafe_sub(value, 2855989394907223263936484059900), value) >> 96, 50020603652535783019961831881945)
                      q = unsafe_sub(unsafe_mul(q, value) >> 96, 533845033583426703283633433725380)
                      q = unsafe_add(unsafe_mul(q, value) >> 96, 3604857256930695427073651918091429)
                      q = unsafe_sub(unsafe_mul(q, value) >> 96, 14423608567350463180887372962807573)
                      q = unsafe_add(unsafe_mul(q, value) >> 96, 26449188498355588339934803723976023)
                  
                      # The polynomial `q` has no zeros in the range because all its roots are complex.
                      # No scaling is required, as `p` is already "2 ** 96" too large. Also,
                      # `r` is in the range "(0.09, 0.25) * 2**96" after the division.
                      r: int256 = unsafe_div(p, q)
                  
                      # To finalise the calculation, we have to multiply `r` by:
                      #   - the scale factor "s = ~6.031367120",
                      #   - the factor "2 ** k" from the range reduction, and
                      #   - the factor "1e18 / 2 ** 96" for the base conversion.
                      # We do this all at once, with an intermediate result in "2**213" base,
                      # so that the final right shift always gives a positive value.
                  
                      # Note that to circumvent Vyper's safecast feature for the potentially
                      # negative parameter value `r`, we first convert `r` to `bytes32` and
                      # subsequently to `uint256`. Remember that the EVM default behaviour is
                      # to use two's complement representation to handle signed integers.
                      return unsafe_mul(convert(convert(r, bytes32), uint256), 3822833074963236453042738258902158003155416615667) >> convert(unsafe_sub(195, k), uint256)
                  
                  
                  # ---------------------------- ERC20 Utils -----------------------------------
                  
                  @view
                  @internal
                  def _domain_separator() -> bytes32:
                      if chain.id != CACHED_CHAIN_ID:
                          return keccak256(
                              _abi_encode(
                                  EIP712_TYPEHASH,
                                  NAME_HASH,
                                  VERSION_HASH,
                                  chain.id,
                                  self,
                                  salt,
                              )
                          )
                      return CACHED_DOMAIN_SEPARATOR
                  
                  
                  @internal
                  def _transfer(_from: address, _to: address, _value: uint256):
                      # # NOTE: vyper does not allow underflows
                      # #       so the following subtraction would revert on insufficient balance
                      self.balanceOf[_from] -= _value
                      self.balanceOf[_to] += _value
                  
                      log Transfer(_from, _to, _value)
                  
                  
                  @internal
                  def _burnFrom(_from: address, _burn_amount: uint256):
                  
                      self.total_supply -= _burn_amount
                      self.balanceOf[_from] -= _burn_amount
                      log Transfer(_from, empty(address), _burn_amount)
                  
                  
                  @external
                  def transfer(_to : address, _value : uint256) -> bool:
                      """
                      @dev Transfer token for a specified address
                      @param _to The address to transfer to.
                      @param _value The amount to be transferred.
                      """
                      self._transfer(msg.sender, _to, _value)
                      return True
                  
                  
                  @external
                  def transferFrom(_from : address, _to : address, _value : uint256) -> bool:
                      """
                       @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 uint256 the amount of tokens to be transferred
                      """
                      self._transfer(_from, _to, _value)
                  
                      _allowance: uint256 = self.allowance[_from][msg.sender]
                      if _allowance != max_value(uint256):
                          _new_allowance: uint256 = _allowance - _value
                          self.allowance[_from][msg.sender] = _new_allowance
                          log Approval(_from, msg.sender, _new_allowance)
                  
                      return True
                  
                  
                  @external
                  def approve(_spender : address, _value : uint256) -> bool:
                      """
                      @notice Approve the passed address to transfer the specified amount of
                              tokens on behalf of msg.sender
                      @dev Beware that changing an allowance via this method brings the risk that
                           someone may use both the old and new allowance by unfortunate transaction
                           ordering: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                      @param _spender The address which will transfer the funds
                      @param _value The amount of tokens that may be transferred
                      @return bool success
                      """
                      self.allowance[msg.sender][_spender] = _value
                  
                      log Approval(msg.sender, _spender, _value)
                      return True
                  
                  
                  @external
                  def permit(
                      _owner: address,
                      _spender: address,
                      _value: uint256,
                      _deadline: uint256,
                      _v: uint8,
                      _r: bytes32,
                      _s: bytes32
                  ) -> bool:
                      """
                      @notice Approves spender by owner's signature to expend owner's tokens.
                          See https://eips.ethereum.org/EIPS/eip-2612.
                      @dev Inspired by https://github.com/yearn/yearn-vaults/blob/main/contracts/Vault.vy#L753-L793
                      @dev Supports smart contract wallets which implement ERC1271
                          https://eips.ethereum.org/EIPS/eip-1271
                      @param _owner The address which is a source of funds and has signed the Permit.
                      @param _spender The address which is allowed to spend the funds.
                      @param _value The amount of tokens to be spent.
                      @param _deadline The timestamp after which the Permit is no longer valid.
                      @param _v The bytes[64] of the valid secp256k1 signature of permit by owner
                      @param _r The bytes[0:32] of the valid secp256k1 signature of permit by owner
                      @param _s The bytes[32:64] of the valid secp256k1 signature of permit by owner
                      @return True, if transaction completes successfully
                      """
                      assert _owner != empty(address)
                      assert block.timestamp <= _deadline
                  
                      nonce: uint256 = self.nonces[_owner]
                      digest: bytes32 = keccak256(
                          concat(
                              b"\x19\x01",
                              self._domain_separator(),
                              keccak256(_abi_encode(EIP2612_TYPEHASH, _owner, _spender, _value, nonce, _deadline))
                          )
                      )
                  
                      if _owner.is_contract:
                          sig: Bytes[65] = concat(_abi_encode(_r, _s), slice(convert(_v, bytes32), 31, 1))
                          # reentrancy not a concern since this is a staticcall
                          assert ERC1271(_owner).isValidSignature(digest, sig) == ERC1271_MAGIC_VAL
                      else:
                          assert ecrecover(digest, convert(_v, uint256), convert(_r, uint256), convert(_s, uint256)) == _owner
                  
                      self.allowance[_owner][_spender] = _value
                      self.nonces[_owner] = unsafe_add(nonce, 1)
                  
                      log Approval(_owner, _spender, _value)
                      return True
                  
                  
                  @view
                  @external
                  def DOMAIN_SEPARATOR() -> bytes32:
                      """
                      @notice EIP712 domain separator.
                      @return bytes32 Domain Separator set for the current chain.
                      """
                      return self._domain_separator()
                  
                  
                  # ------------------------- AMM View Functions -------------------------------
                  
                  
                  @view
                  @external
                  def get_dx(i: int128, j: int128, dy: uint256) -> uint256:
                      """
                      @notice Calculate the current input dx given output dy
                      @dev Index values can be found via the `coins` public getter method
                      @param i Index value for the coin to send
                      @param j Index value of the coin to receive
                      @param dy Amount of `j` being received after exchange
                      @return Amount of `i` predicted
                      """
                      return StableSwapViews(factory.views_implementation()).get_dx(i, j, dy, self)
                  
                  
                  @view
                  @external
                  def get_dy(i: int128, j: int128, dx: uint256) -> uint256:
                      """
                      @notice Calculate the current output dy given input dx
                      @dev Index values can be found via the `coins` public getter method
                      @param i Index value for the coin to send
                      @param j Index value of the coin to receive
                      @param dx Amount of `i` being exchanged
                      @return Amount of `j` predicted
                      """
                      return StableSwapViews(factory.views_implementation()).get_dy(i, j, dx, self)
                  
                  
                  @view
                  @external
                  def calc_withdraw_one_coin(_burn_amount: uint256, i: int128) -> uint256:
                      """
                      @notice Calculate the amount received when withdrawing a single coin
                      @param _burn_amount Amount of LP tokens to burn in the withdrawal
                      @param i Index value of the coin to withdraw
                      @return Amount of coin received
                      """
                      return self._calc_withdraw_one_coin(_burn_amount, i)[0]
                  
                  
                  @view
                  @external
                  @nonreentrant('lock')
                  def totalSupply() -> uint256:
                      """
                      @notice The total supply of pool LP tokens
                      @return self.total_supply, 18 decimals.
                      """
                      return self.total_supply
                  
                  
                  @view
                  @external
                  @nonreentrant('lock')
                  def get_virtual_price() -> uint256:
                      """
                      @notice The current virtual price of the pool LP token
                      @dev Useful for calculating profits.
                           The method may be vulnerable to donation-style attacks if implementation
                           contains rebasing tokens. For integrators, caution is advised.
                      @return LP token virtual price normalized to 1e18
                      """
                      amp: uint256 = self._A()
                      xp: DynArray[uint256, MAX_COINS] = self._xp_mem(
                          self._stored_rates(), self._balances()
                      )
                      D: uint256 = self.get_D(xp, amp)
                      # D is in the units similar to DAI (e.g. converted to precision 1e18)
                      # When balanced, D = n * x_u - total virtual value of the portfolio
                      return D * PRECISION / self.total_supply
                  
                  
                  @view
                  @external
                  def calc_token_amount(
                      _amounts: DynArray[uint256, MAX_COINS],
                      _is_deposit: bool
                  ) -> uint256:
                      """
                      @notice Calculate addition or reduction in token supply from a deposit or withdrawal
                      @param _amounts Amount of each coin being deposited
                      @param _is_deposit set True for deposits, False for withdrawals
                      @return Expected amount of LP tokens received
                      """
                      return StableSwapViews(factory.views_implementation()).calc_token_amount(_amounts, _is_deposit, self)
                  
                  
                  @view
                  @external
                  def A() -> uint256:
                      return unsafe_div(self._A(), A_PRECISION)
                  
                  
                  @view
                  @external
                  def A_precise() -> uint256:
                      return self._A()
                  
                  
                  @view
                  @external
                  def balances(i: uint256) -> uint256:
                      """
                      @notice Get the current balance of a coin within the
                              pool, less the accrued admin fees
                      @param i Index value for the coin to query balance of
                      @return Token balance
                      """
                      return self._balances()[i]
                  
                  
                  @view
                  @external
                  def get_balances() -> DynArray[uint256, MAX_COINS]:
                      return self._balances()
                  
                  
                  @view
                  @external
                  def stored_rates() -> DynArray[uint256, MAX_COINS]:
                      return self._stored_rates()
                  
                  
                  @view
                  @external
                  def dynamic_fee(i: int128, j: int128) -> uint256:
                      """
                      @notice Return the fee for swapping between `i` and `j`
                      @param i Index value for the coin to send
                      @param j Index value of the coin to receive
                      @return Swap fee expressed as an integer with 1e10 precision
                      """
                      return StableSwapViews(factory.views_implementation()).dynamic_fee(i, j, self)
                  
                  
                  # --------------------------- AMM Admin Functions ----------------------------
                  
                  
                  @external
                  def ramp_A(_future_A: uint256, _future_time: uint256):
                      assert msg.sender == factory.admin()  # dev: only owner
                      assert block.timestamp >= self.initial_A_time + MIN_RAMP_TIME
                      assert _future_time >= block.timestamp + MIN_RAMP_TIME  # dev: insufficient time
                  
                      _initial_A: uint256 = self._A()
                      _future_A_p: uint256 = _future_A * A_PRECISION
                  
                      assert _future_A > 0 and _future_A < MAX_A
                      if _future_A_p < _initial_A:
                          assert _future_A_p * MAX_A_CHANGE >= _initial_A
                      else:
                          assert _future_A_p <= _initial_A * MAX_A_CHANGE
                  
                      self.initial_A = _initial_A
                      self.future_A = _future_A_p
                      self.initial_A_time = block.timestamp
                      self.future_A_time = _future_time
                  
                      log RampA(_initial_A, _future_A_p, block.timestamp, _future_time)
                  
                  
                  @external
                  def stop_ramp_A():
                      assert msg.sender == factory.admin()  # dev: only owner
                  
                      current_A: uint256 = self._A()
                      self.initial_A = current_A
                      self.future_A = current_A
                      self.initial_A_time = block.timestamp
                      self.future_A_time = block.timestamp
                      # now (block.timestamp < t1) is always False, so we return saved A
                  
                      log StopRampA(current_A, block.timestamp)
                  
                  
                  @external
                  def set_new_fee(_new_fee: uint256, _new_offpeg_fee_multiplier: uint256):
                  
                      assert msg.sender == factory.admin()
                  
                      # set new fee:
                      assert _new_fee <= MAX_FEE
                      self.fee = _new_fee
                  
                      # set new offpeg_fee_multiplier:
                      assert _new_offpeg_fee_multiplier * _new_fee <= MAX_FEE * FEE_DENOMINATOR  # dev: offpeg multiplier exceeds maximum
                      self.offpeg_fee_multiplier = _new_offpeg_fee_multiplier
                  
                      log ApplyNewFee(_new_fee, _new_offpeg_fee_multiplier)
                  
                  
                  @external
                  def set_ma_exp_time(_ma_exp_time: uint256, _D_ma_time: uint256):
                      """
                      @notice Set the moving average window of the price oracles.
                      @param _ma_exp_time Moving average window for the price oracle. It is time_in_seconds / ln(2).
                      @param _D_ma_time Moving average window for the D oracle. It is time_in_seconds / ln(2).
                      """
                      assert msg.sender == factory.admin()  # dev: only owner
                      assert unsafe_mul(_ma_exp_time, _D_ma_time) > 0  # dev: 0 in input values
                  
                      self.ma_exp_time = _ma_exp_time
                      self.D_ma_time = _D_ma_time
                  
                      log SetNewMATime(_ma_exp_time, _D_ma_time)

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