ETH Price: $3,285.47 (-4.38%)

Transaction Decoder

Block:
21973798 at Mar-04-2025 01:23:23 PM +UTC
Transaction Fee:
0.00011040805401522 ETH $0.36
Gas Used:
73,762 Gas / 1.49681481 Gwei

Emitted Events:

66 InitializableAdminUpgradeabilityProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000005dc62cea20b0e7c3607adcc61a885ff9369dbc60, 0x000000000000000000000000fe9cb5423f54c8d69917c5beeb8c00503b4a1a91, 0000000000000000000000000000000000000000000000139270cf5c610d8e51 )

Account State Difference:

  Address   Before After State Difference Code
0x7Fc66500...33E2DDaE9
0xaF3960e0...258962c22
18.70349541552595085 Eth
Nonce: 40863
18.70338500747193563 Eth
Nonce: 40864
0.00011040805401522
0.098937675188877453 Eth0.098944247658799809 Eth0.000006572469922356

Execution Trace

0x5dc62cea20b0e7c3607adcc61a885ff9369dbc60.f5537ede( )
  • InitializableAdminUpgradeabilityProxy.a9059cbb( )
    • AaveTokenV3.transfer( to=0xfe9CB5423f54C8d69917c5bEeb8c00503B4a1A91, amount=361040299323082772049 ) => ( True )
      File 1 of 2: InitializableAdminUpgradeabilityProxy
      // SPDX-License-Identifier: agpl-3.0
      pragma solidity 0.6.10;
      /**
       * @dev Interface of the ERC20 standard as defined in the EIP.
       */
      interface IERC20 {
          /**
           * @dev Returns the amount of tokens in existence.
           */
          function totalSupply() external view returns (uint256);
          /**
           * @dev Returns the amount of tokens owned by `account`.
           */
          function balanceOf(address account) external view returns (uint256);
          /**
           * @dev Moves `amount` tokens from the caller's account to `recipient`.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * Emits a {Transfer} event.
           */
          function transfer(address recipient, uint256 amount) external returns (bool);
          /**
           * @dev Returns the remaining number of tokens that `spender` will be
           * allowed to spend on behalf of `owner` through {transferFrom}. This is
           * zero by default.
           *
           * This value changes when {approve} or {transferFrom} are called.
           */
          function allowance(address owner, address spender) external view returns (uint256);
          /**
           * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * IMPORTANT: Beware that changing an allowance with this method brings the risk
           * that someone may use both the old and the new allowance by unfortunate
           * transaction ordering. One possible solution to mitigate this race
           * condition is to first reduce the spender's allowance to 0 and set the
           * desired value afterwards:
           * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
           *
           * Emits an {Approval} event.
           */
          function approve(address spender, uint256 amount) external returns (bool);
          /**
           * @dev Moves `amount` tokens from `sender` to `recipient` using the
           * allowance mechanism. `amount` is then deducted from the caller's
           * allowance.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * Emits a {Transfer} event.
           */
          function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
          /**
           * @dev Emitted when `value` tokens are moved from one account (`from`) to
           * another (`to`).
           *
           * Note that `value` may be zero.
           */
          event Transfer(address indexed from, address indexed to, uint256 value);
          /**
           * @dev Emitted when the allowance of a `spender` for an `owner` is set by
           * a call to {approve}. `value` is the new allowance.
           */
          event Approval(address indexed owner, address indexed spender, uint256 value);
      }// SPDX-License-Identifier: agpl-3.0
      pragma solidity 0.6.10;
      import {IERC20} from "./IERC20.sol";
      interface IERC20Detailed is IERC20 {
          function name() external view returns(string memory);
          function symbol() external view returns(string memory);
          function decimals() external view returns(uint8);
      }
      // SPDX-License-Identifier: agpl-3.0
      pragma solidity 0.6.10;
      interface ITransferHook {
          function onTransfer(address from, address to, uint256 amount) external;
      }pragma solidity ^0.6.2;
      /**
       * @dev Collection of functions related to the address type
       */
      library Address {
          /**
           * @dev Returns true if `account` is a contract.
           *
           * [IMPORTANT]
           * ====
           * It is unsafe to assume that an address for which this function returns
           * false is an externally-owned account (EOA) and not a contract.
           *
           * Among others, `isContract` will return false for the following
           * types of addresses:
           *
           *  - an externally-owned account
           *  - a contract in construction
           *  - an address where a contract will be created
           *  - an address where a contract lived, but was destroyed
           * ====
           */
          function isContract(address account) internal view returns (bool) {
              // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
              // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
              // for accounts without code, i.e. `keccak256('')`
              bytes32 codehash;
              bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
              // solhint-disable-next-line no-inline-assembly
              assembly { codehash := extcodehash(account) }
              return (codehash != accountHash && codehash != 0x0);
          }
          /**
           * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
           * `recipient`, forwarding all available gas and reverting on errors.
           *
           * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
           * of certain opcodes, possibly making contracts go over the 2300 gas limit
           * imposed by `transfer`, making them unable to receive funds via
           * `transfer`. {sendValue} removes this limitation.
           *
           * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
           *
           * IMPORTANT: because control is transferred to `recipient`, care must be
           * taken to not create reentrancy vulnerabilities. Consider using
           * {ReentrancyGuard} or the
           * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
           */
          function sendValue(address payable recipient, uint256 amount) internal {
              require(address(this).balance >= amount, "Address: insufficient balance");
              // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
              (bool success, ) = recipient.call{ value: amount }("");
              require(success, "Address: unable to send value, recipient may have reverted");
          }
      }pragma solidity ^0.6.0;
      import './UpgradeabilityProxy.sol';
      /**
       * @title BaseAdminUpgradeabilityProxy
       * @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 BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
        /**
         * @dev Emitted when the administration has been transferred.
         * @param previousAdmin Address of the previous admin.
         * @param newAdmin Address of the new admin.
         */
        event AdminChanged(address previousAdmin, address newAdmin);
        /**
         * @dev Storage slot with the admin of the contract.
         * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
         * validated in the constructor.
         */
        bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
        /**
         * @dev Modifier to check whether the `msg.sender` is the admin.
         * If it is, it will run the function. Otherwise, it will delegate the call
         * to the implementation.
         */
        modifier ifAdmin() {
          if (msg.sender == _admin()) {
            _;
          } else {
            _fallback();
          }
        }
        /**
         * @return The address of the proxy admin.
         */
        function admin() external ifAdmin returns (address) {
          return _admin();
        }
        /**
         * @return The address of the implementation.
         */
        function implementation() external ifAdmin returns (address) {
          return _implementation();
        }
        /**
         * @dev Changes the admin of the proxy.
         * Only the current admin can call this function.
         * @param newAdmin Address to transfer proxy administration to.
         */
        function changeAdmin(address newAdmin) external ifAdmin {
          require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
          emit AdminChanged(_admin(), newAdmin);
          _setAdmin(newAdmin);
        }
        /**
         * @dev Upgrade the backing implementation of the proxy.
         * Only the admin can call this function.
         * @param newImplementation Address of the new implementation.
         */
        function upgradeTo(address newImplementation) external ifAdmin {
          _upgradeTo(newImplementation);
        }
        /**
         * @dev Upgrade the backing implementation of the proxy and call a function
         * on the new implementation.
         * This is useful to initialize the proxied contract.
         * @param newImplementation Address of the new implementation.
         * @param data Data to send as msg.data in the low level call.
         * It should include the signature and the parameters of the function to be called, as described in
         * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
         */
        function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
          _upgradeTo(newImplementation);
          (bool success,) = newImplementation.delegatecall(data);
          require(success);
        }
        /**
         * @return adm The admin slot.
         */
        function _admin() internal view returns (address adm) {
          bytes32 slot = ADMIN_SLOT;
          assembly {
            adm := sload(slot)
          }
        }
        /**
         * @dev Sets the address of the proxy admin.
         * @param newAdmin Address of the new proxy admin.
         */
        function _setAdmin(address newAdmin) internal {
          bytes32 slot = ADMIN_SLOT;
          assembly {
            sstore(slot, newAdmin)
          }
        }
        /**
         * @dev Only fall back when the sender is not the admin.
         */
        function _willFallback() internal override virtual {
          require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
          super._willFallback();
        }
      }pragma solidity ^0.6.0;
      import './BaseUpgradeabilityProxy.sol';
      /**
       * @title UpgradeabilityProxy
       * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
       * implementation and init data.
       */
      contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
        /**
         * @dev Contract constructor.
         * @param _logic Address of the initial implementation.
         * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
         * It should include the signature and the parameters of the function to be called, as described in
         * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
         * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
         */
        constructor(address _logic, bytes memory _data) public payable {
          assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
          _setImplementation(_logic);
          if(_data.length > 0) {
            (bool success,) = _logic.delegatecall(_data);
            require(success);
          }
        }  
      }pragma solidity ^0.6.0;
      import './Proxy.sol';
      import './Address.sol';
      /**
       * @title BaseUpgradeabilityProxy
       * @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 BaseUpgradeabilityProxy is Proxy {
        /**
         * @dev Emitted when the implementation is upgraded.
         * @param implementation Address of the new implementation.
         */
        event Upgraded(address indexed implementation);
        /**
         * @dev Storage slot with the address of the current implementation.
         * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
         * validated in the constructor.
         */
        bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
        /**
         * @dev Returns the current implementation.
         * @return impl Address of the current implementation
         */
        function _implementation() internal override view returns (address impl) {
          bytes32 slot = IMPLEMENTATION_SLOT;
          assembly {
            impl := sload(slot)
          }
        }
        /**
         * @dev Upgrades the proxy to a new implementation.
         * @param newImplementation Address of the new implementation.
         */
        function _upgradeTo(address newImplementation) internal {
          _setImplementation(newImplementation);
          emit Upgraded(newImplementation);
        }
        /**
         * @dev Sets the implementation address of the proxy.
         * @param newImplementation Address of the new implementation.
         */
        function _setImplementation(address newImplementation) internal {
          require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
          bytes32 slot = IMPLEMENTATION_SLOT;
          assembly {
            sstore(slot, newImplementation)
          }
        }
      }pragma solidity ^0.6.0;
      /**
       * @title Proxy
       * @dev Implements delegation of calls to other contracts, with proper
       * forwarding of return values and bubbling of failures.
       * It defines a fallback function that delegates all calls to the address
       * returned by the abstract _implementation() internal function.
       */
      abstract contract Proxy {
        /**
         * @dev Fallback function.
         * Implemented entirely in `_fallback`.
         */
        fallback () payable external {
          _fallback();
        }
        /**
         * @return The Address of the implementation.
         */
        function _implementation() internal virtual view returns (address);
        /**
         * @dev Delegates execution to an implementation contract.
         * This is a low level function that doesn't return to its internal call site.
         * It will return to the external caller whatever the implementation returns.
         * @param implementation Address to delegate.
         */
        function _delegate(address implementation) internal {
          assembly {
            // Copy msg.data. We take full control of memory in this inline assembly
            // block because it will not return to Solidity code. We overwrite the
            // Solidity scratch pad at memory position 0.
            calldatacopy(0, 0, calldatasize())
            // Call the implementation.
            // out and outsize are 0 because we don't know the size yet.
            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
            // Copy the returned data.
            returndatacopy(0, 0, returndatasize())
            switch result
            // delegatecall returns 0 on error.
            case 0 { revert(0, returndatasize()) }
            default { return(0, returndatasize()) }
          }
        }
        /**
         * @dev Function that is run as the first thing in the fallback function.
         * Can be redefined in derived contracts to add functionality.
         * Redefinitions must call super._willFallback().
         */
        function _willFallback() internal virtual {
        }
        /**
         * @dev fallback implementation.
         * Extracted to enable manual triggering.
         */
        function _fallback() internal {
          _willFallback();
          _delegate(_implementation());
        }
      }// SPDX-License-Identifier: MIT
      pragma solidity ^0.6.0;
      /*
       * @dev Provides information about the current execution context, including the
       * sender of the transaction and its data. While these are generally available
       * via msg.sender and msg.data, they should not be accessed in such a direct
       * manner, since when dealing with GSN meta-transactions the account sending and
       * paying for execution may not be the actual sender (as far as an application
       * is concerned).
       *
       * This contract is only required for intermediate, library-like contracts.
       */
      abstract contract Context {
          function _msgSender() internal view virtual returns (address payable) {
              return msg.sender;
          }
          function _msgData() internal view virtual returns (bytes memory) {
              this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
              return msg.data;
          }
      }// SPDX-License-Identifier: MIT
      pragma solidity ^0.6.0;
      import "./Context.sol";
      import "../interfaces/IERC20.sol";
      import "./SafeMath.sol";
      import "./Address.sol";
      /**
       * @dev Implementation of the {IERC20} interface.
       *
       * This implementation is agnostic to the way tokens are created. This means
       * that a supply mechanism has to be added in a derived contract using {_mint}.
       * For a generic mechanism see {ERC20PresetMinterPauser}.
       *
       * TIP: For a detailed writeup see our guide
       * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
       * to implement supply mechanisms].
       *
       * We have followed general OpenZeppelin guidelines: functions revert instead
       * of returning `false` on failure. This behavior is nonetheless conventional
       * and does not conflict with the expectations of ERC20 applications.
       *
       * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
       * This allows applications to reconstruct the allowance for all accounts just
       * by listening to said events. Other implementations of the EIP may not emit
       * these events, as it isn't required by the specification.
       *
       * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
       * functions have been added to mitigate the well-known issues around setting
       * allowances. See {IERC20-approve}.
       */
      contract ERC20 is Context, IERC20 {
          using SafeMath for uint256;
          using Address for address;
          mapping (address => uint256) private _balances;
          mapping (address => mapping (address => uint256)) private _allowances;
          uint256 private _totalSupply;
          string internal _name;
          string internal _symbol;
          uint8 private _decimals;
          /**
           * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
           * a default value of 18.
           *
           * To select a different value for {decimals}, use {_setupDecimals}.
           *
           * All three of these values are immutable: they can only be set once during
           * construction.
           */
          constructor (string memory name, string memory symbol) public {
              _name = name;
              _symbol = symbol;
              _decimals = 18;
          }
          /**
           * @dev Returns the name of the token.
           */
          function name() public view returns (string memory) {
              return _name;
          }
          /**
           * @dev Returns the symbol of the token, usually a shorter version of the
           * name.
           */
          function symbol() public view returns (string memory) {
              return _symbol;
          }
          /**
           * @dev Returns the number of decimals used to get its user representation.
           * For example, if `decimals` equals `2`, a balance of `505` tokens should
           * be displayed to a user as `5,05` (`505 / 10 ** 2`).
           *
           * Tokens usually opt for a value of 18, imitating the relationship between
           * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
           * called.
           *
           * NOTE: This information is only used for _display_ purposes: it in
           * no way affects any of the arithmetic of the contract, including
           * {IERC20-balanceOf} and {IERC20-transfer}.
           */
          function decimals() public view returns (uint8) {
              return _decimals;
          }
          /**
           * @dev See {IERC20-totalSupply}.
           */
          function totalSupply() public view override returns (uint256) {
              return _totalSupply;
          }
          /**
           * @dev See {IERC20-balanceOf}.
           */
          function balanceOf(address account) public view override returns (uint256) {
              return _balances[account];
          }
          /**
           * @dev See {IERC20-transfer}.
           *
           * Requirements:
           *
           * - `recipient` cannot be the zero address.
           * - the caller must have a balance of at least `amount`.
           */
          function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
              _transfer(_msgSender(), recipient, amount);
              return true;
          }
          /**
           * @dev See {IERC20-allowance}.
           */
          function allowance(address owner, address spender) public view virtual override returns (uint256) {
              return _allowances[owner][spender];
          }
          /**
           * @dev See {IERC20-approve}.
           *
           * Requirements:
           *
           * - `spender` cannot be the zero address.
           */
          function approve(address spender, uint256 amount) public virtual override returns (bool) {
              _approve(_msgSender(), spender, amount);
              return true;
          }
          /**
           * @dev See {IERC20-transferFrom}.
           *
           * Emits an {Approval} event indicating the updated allowance. This is not
           * required by the EIP. See the note at the beginning of {ERC20};
           *
           * Requirements:
           * - `sender` and `recipient` cannot be the zero address.
           * - `sender` must have a balance of at least `amount`.
           * - the caller must have allowance for ``sender``'s tokens of at least
           * `amount`.
           */
          function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
              _transfer(sender, recipient, amount);
              _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
              return true;
          }
          /**
           * @dev Atomically increases the allowance granted to `spender` by the caller.
           *
           * This is an alternative to {approve} that can be used as a mitigation for
           * problems described in {IERC20-approve}.
           *
           * Emits an {Approval} event indicating the updated allowance.
           *
           * Requirements:
           *
           * - `spender` cannot be the zero address.
           */
          function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
              _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
              return true;
          }
          /**
           * @dev Atomically decreases the allowance granted to `spender` by the caller.
           *
           * This is an alternative to {approve} that can be used as a mitigation for
           * problems described in {IERC20-approve}.
           *
           * Emits an {Approval} event indicating the updated allowance.
           *
           * Requirements:
           *
           * - `spender` cannot be the zero address.
           * - `spender` must have allowance for the caller of at least
           * `subtractedValue`.
           */
          function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
              _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
              return true;
          }
          /**
           * @dev Moves tokens `amount` from `sender` to `recipient`.
           *
           * This is internal function is equivalent to {transfer}, and can be used to
           * e.g. implement automatic token fees, slashing mechanisms, etc.
           *
           * Emits a {Transfer} event.
           *
           * Requirements:
           *
           * - `sender` cannot be the zero address.
           * - `recipient` cannot be the zero address.
           * - `sender` must have a balance of at least `amount`.
           */
          function _transfer(address sender, address recipient, uint256 amount) internal virtual {
              require(sender != address(0), "ERC20: transfer from the zero address");
              require(recipient != address(0), "ERC20: transfer to the zero address");
              _beforeTokenTransfer(sender, recipient, amount);
              _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
              _balances[recipient] = _balances[recipient].add(amount);
              emit Transfer(sender, recipient, amount);
          }
          /** @dev Creates `amount` tokens and assigns them to `account`, increasing
           * the total supply.
           *
           * Emits a {Transfer} event with `from` set to the zero address.
           *
           * Requirements
           *
           * - `to` cannot be the zero address.
           */
          function _mint(address account, uint256 amount) internal virtual {
              require(account != address(0), "ERC20: mint to the zero address");
              _beforeTokenTransfer(address(0), account, amount);
              _totalSupply = _totalSupply.add(amount);
              _balances[account] = _balances[account].add(amount);
              emit Transfer(address(0), account, amount);
          }
          /**
           * @dev Destroys `amount` tokens from `account`, reducing the
           * total supply.
           *
           * Emits a {Transfer} event with `to` set to the zero address.
           *
           * Requirements
           *
           * - `account` cannot be the zero address.
           * - `account` must have at least `amount` tokens.
           */
          function _burn(address account, uint256 amount) internal virtual {
              require(account != address(0), "ERC20: burn from the zero address");
              _beforeTokenTransfer(account, address(0), amount);
              _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
              _totalSupply = _totalSupply.sub(amount);
              emit Transfer(account, address(0), amount);
          }
          /**
           * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
           *
           * This is internal function is equivalent to `approve`, and can be used to
           * e.g. set automatic allowances for certain subsystems, etc.
           *
           * Emits an {Approval} event.
           *
           * Requirements:
           *
           * - `owner` cannot be the zero address.
           * - `spender` cannot be the zero address.
           */
          function _approve(address owner, address spender, uint256 amount) internal virtual {
              require(owner != address(0), "ERC20: approve from the zero address");
              require(spender != address(0), "ERC20: approve to the zero address");
              _allowances[owner][spender] = amount;
              emit Approval(owner, spender, amount);
          }
          /**
           * @dev Sets {decimals} to a value other than the default one of 18.
           *
           * WARNING: This function should only be called from the constructor. Most
           * applications that interact with token contracts will not expect
           * {decimals} to ever change, and may work incorrectly if it does.
           */
          function _setupDecimals(uint8 decimals_) internal {
              _decimals = decimals_;
          }
          /**
           * @dev Hook that is called before any transfer of tokens. This includes
           * minting and burning.
           *
           * Calling conditions:
           *
           * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
           * will be to transferred to `to`.
           * - when `from` is zero, `amount` tokens will be minted for `to`.
           * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
           * - `from` and `to` are never both zero.
           *
           * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
           */
          function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
      }pragma solidity ^0.6.0;
      /**
       * @dev Wrappers over Solidity's arithmetic operations with added overflow
       * checks.
       *
       * Arithmetic operations in Solidity wrap on overflow. This can easily result
       * in bugs, because programmers usually assume that an overflow raises an
       * error, which is the standard behavior in high level programming languages.
       * `SafeMath` restores this intuition by reverting the transaction when an
       * operation overflows.
       *
       * Using this library instead of the unchecked operations eliminates an entire
       * class of bugs, so it's recommended to use it always.
       */
      library SafeMath {
          /**
           * @dev Returns the addition of two unsigned integers, reverting on
           * overflow.
           *
           * Counterpart to Solidity's `+` operator.
           *
           * Requirements:
           * - Addition cannot overflow.
           */
          function add(uint256 a, uint256 b) internal pure returns (uint256) {
              uint256 c = a + b;
              require(c >= a, "SafeMath: addition overflow");
              return c;
          }
          /**
           * @dev Returns the subtraction of two unsigned integers, reverting on
           * overflow (when the result is negative).
           *
           * Counterpart to Solidity's `-` operator.
           *
           * Requirements:
           * - Subtraction cannot overflow.
           */
          function sub(uint256 a, uint256 b) internal pure returns (uint256) {
              return sub(a, b, "SafeMath: subtraction overflow");
          }
          /**
           * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
           * overflow (when the result is negative).
           *
           * Counterpart to Solidity's `-` operator.
           *
           * Requirements:
           * - Subtraction cannot overflow.
           */
          function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
              require(b <= a, errorMessage);
              uint256 c = a - b;
              return c;
          }
          /**
           * @dev Returns the multiplication of two unsigned integers, reverting on
           * overflow.
           *
           * Counterpart to Solidity's `*` operator.
           *
           * Requirements:
           * - Multiplication cannot overflow.
           */
          function mul(uint256 a, uint256 b) internal pure returns (uint256) {
              // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
              // benefit is lost if 'b' is also tested.
              // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
              if (a == 0) {
                  return 0;
              }
              uint256 c = a * b;
              require(c / a == b, "SafeMath: multiplication overflow");
              return c;
          }
          /**
           * @dev Returns the integer division of two unsigned integers. Reverts on
           * division by zero. The result is rounded towards zero.
           *
           * Counterpart to Solidity's `/` operator. Note: this function uses a
           * `revert` opcode (which leaves remaining gas untouched) while Solidity
           * uses an invalid opcode to revert (consuming all remaining gas).
           *
           * Requirements:
           * - The divisor cannot be zero.
           */
          function div(uint256 a, uint256 b) internal pure returns (uint256) {
              return div(a, b, "SafeMath: division by zero");
          }
          /**
           * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
           * division by zero. The result is rounded towards zero.
           *
           * Counterpart to Solidity's `/` operator. Note: this function uses a
           * `revert` opcode (which leaves remaining gas untouched) while Solidity
           * uses an invalid opcode to revert (consuming all remaining gas).
           *
           * Requirements:
           * - The divisor cannot be zero.
           */
          function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
              // Solidity only automatically asserts when dividing by 0
              require(b > 0, errorMessage);
              uint256 c = a / b;
              // assert(a == b * c + a % b); // There is no case in which this doesn't hold
              return c;
          }
          /**
           * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
           * Reverts when dividing by zero.
           *
           * Counterpart to Solidity's `%` operator. This function uses a `revert`
           * opcode (which leaves remaining gas untouched) while Solidity uses an
           * invalid opcode to revert (consuming all remaining gas).
           *
           * Requirements:
           * - The divisor cannot be zero.
           */
          function mod(uint256 a, uint256 b) internal pure returns (uint256) {
              return mod(a, b, "SafeMath: modulo by zero");
          }
          /**
           * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
           * Reverts with custom message when dividing by zero.
           *
           * Counterpart to Solidity's `%` operator. This function uses a `revert`
           * opcode (which leaves remaining gas untouched) while Solidity uses an
           * invalid opcode to revert (consuming all remaining gas).
           *
           * Requirements:
           * - The divisor cannot be zero.
           */
          function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
              require(b != 0, errorMessage);
              return a % b;
          }
      }// SPDX-License-Identifier: agpl-3.0
      pragma solidity ^0.6.10;
      import "./BaseAdminUpgradeabilityProxy.sol";
      import "./InitializableUpgradeabilityProxy.sol";
      /**
       * @title InitializableAdminUpgradeabilityProxy
       * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for 
       * initializing the implementation, admin, and init data.
       */
      contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
          /**
         * Contract initializer.
         * @param _logic address of the initial implementation.
         * @param _admin Address of the proxy administrator.
         * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
         * It should include the signature and the parameters of the function to be called, as described in
         * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
         * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
         */
          function initialize(address _logic, address _admin, bytes memory _data) public payable {
              require(_implementation() == address(0));
              InitializableUpgradeabilityProxy.initialize(_logic, _data);
              assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
              _setAdmin(_admin);
          }
          /**
          * @dev Only fall back when the sender is not the admin.
          */
          function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) {
              BaseAdminUpgradeabilityProxy._willFallback();
          }
      }
      // SPDX-License-Identifier: agpl-3.0
      pragma solidity ^0.6.10;
      import "./BaseUpgradeabilityProxy.sol";
      /**
       * @title InitializableUpgradeabilityProxy
       * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
       * implementation and init data.
       */
      contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
          /**
         * @dev Contract initializer.
         * @param _logic Address of the initial implementation.
         * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
         * It should include the signature and the parameters of the function to be called, as described in
         * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
         * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
         */
          function initialize(address _logic, bytes memory _data) public payable {
              require(_implementation() == address(0));
              assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
              _setImplementation(_logic);
              if (_data.length > 0) {
                  (bool success, ) = _logic.delegatecall(_data);
                  require(success);
              }
          }
      }
      // SPDX-License-Identifier: agpl-3.0
      pragma solidity 0.6.10;
      import {ERC20} from "../open-zeppelin/ERC20.sol";
      import {ITransferHook} from "../interfaces/ITransferHook.sol";
      import {VersionedInitializable} from "../utils/VersionedInitializable.sol";
      /**
      * @notice implementation of the AAVE token contract
      * @author Aave
      */
      contract AaveToken is ERC20, VersionedInitializable {
          /// @dev snapshot of a value on a specific block, used for balances
          struct Snapshot {
              uint128 blockNumber;
              uint128 value;
          }
          string internal constant NAME = "Aave Token";
          string internal constant SYMBOL = "AAVE";
          uint8 internal constant DECIMALS = 18;
          /// @dev the amount being distributed for the LEND -> AAVE migration
          uint256 internal constant MIGRATION_AMOUNT = 13000000 ether;
          /// @dev the amount being distributed for the PSI and PEI
          uint256 internal constant DISTRIBUTION_AMOUNT = 3000000 ether;
          uint256 public constant REVISION = 1;
          /// @dev owner => next valid nonce to submit with permit()
          mapping (address => uint256) public _nonces;
          mapping (address => mapping (uint256 => Snapshot)) public _snapshots;
          mapping (address => uint256) public _countsSnapshots;
          /// @dev reference to the Aave governance contract to call (if initialized) on _beforeTokenTransfer
          /// !!! IMPORTANT The Aave governance is considered a trustable contract, being its responsibility
          /// to control all potential reentrancies by calling back the AaveToken
          ITransferHook public _aaveGovernance;
          bytes32 public DOMAIN_SEPARATOR;
          bytes public constant EIP712_REVISION = bytes("1");
          bytes32 internal constant EIP712_DOMAIN = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
          bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
          event SnapshotDone(address owner, uint128 oldValue, uint128 newValue);
          constructor() ERC20(NAME, SYMBOL) public {}
          /**
          * @dev initializes the contract upon assignment to the InitializableAdminUpgradeabilityProxy
          * @param migrator the address of the LEND -> AAVE migration contract
          * @param distributor the address of the AAVE distribution contract
          */
          function initialize(
              address migrator,
              address distributor,
              ITransferHook aaveGovernance
          ) external initializer {
              uint256 chainId;
              //solium-disable-next-line
              assembly {
                  chainId := chainid()
              }
              DOMAIN_SEPARATOR = keccak256(abi.encode(
                  EIP712_DOMAIN,
                  keccak256(bytes(NAME)),
                  keccak256(EIP712_REVISION),
                  chainId,
                  address(this)
              ));
              _name = NAME;
              _symbol = SYMBOL;
              _setupDecimals(DECIMALS);
              _aaveGovernance = aaveGovernance;
              _mint(migrator, MIGRATION_AMOUNT);
              _mint(distributor, DISTRIBUTION_AMOUNT);
          }
          /**
          * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
          * @param owner the owner of the funds
          * @param spender the spender
          * @param value the amount
          * @param deadline the deadline timestamp, type(uint256).max for no deadline
          * @param v signature param
          * @param s signature param
          * @param r signature param
          */
          function permit(
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) external {
              require(owner != address(0), "INVALID_OWNER");
              //solium-disable-next-line
              require(block.timestamp <= deadline, "INVALID_EXPIRATION");
              uint256 currentValidNonce = _nonces[owner];
              bytes32 digest = keccak256(
                      abi.encodePacked(
                          "\\x19\\x01",
                          DOMAIN_SEPARATOR,
                          keccak256(
                              abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline))
                          )
              );
              require(owner == ecrecover(digest, v, r, s), "INVALID_SIGNATURE");
              _nonces[owner] = currentValidNonce.add(1);
              _approve(owner, spender, value);
          }
          /**
          * @dev returns the revision of the implementation contract
          */
          function getRevision() internal pure override returns (uint256) {
              return REVISION;
          }
          /**
          * @dev Writes a snapshot for an owner of tokens
          * @param owner The owner of the tokens
          * @param oldValue The value before the operation that is gonna be executed after the snapshot
          * @param newValue The value after the operation
          */
          function _writeSnapshot(address owner, uint128 oldValue, uint128 newValue) internal {
              uint128 currentBlock = uint128(block.number);
              uint256 ownerCountOfSnapshots = _countsSnapshots[owner];
              mapping (uint256 => Snapshot) storage snapshotsOwner = _snapshots[owner];
              // Doing multiple operations in the same block
              if (ownerCountOfSnapshots != 0 && snapshotsOwner[ownerCountOfSnapshots.sub(1)].blockNumber == currentBlock) {
                  snapshotsOwner[ownerCountOfSnapshots.sub(1)].value = newValue;
              } else {
                  snapshotsOwner[ownerCountOfSnapshots] = Snapshot(currentBlock, newValue);
                  _countsSnapshots[owner] = ownerCountOfSnapshots.add(1);
              }
              emit SnapshotDone(owner, oldValue, newValue);
          }
          /**
          * @dev Writes a snapshot before any operation involving transfer of value: _transfer, _mint and _burn
          * - On _transfer, it writes snapshots for both "from" and "to"
          * - On _mint, only for _to
          * - On _burn, only for _from
          * @param from the from address
          * @param to the to address
          * @param amount the amount to transfer
          */
          function _beforeTokenTransfer(address from, address to, uint256 amount) internal override {
              if (from == to) {
                  return;
              }
              if (from != address(0)) {
                  uint256 fromBalance = balanceOf(from);
                  _writeSnapshot(from, uint128(fromBalance), uint128(fromBalance.sub(amount)));
              }
              if (to != address(0)) {
                  uint256 toBalance = balanceOf(to);
                  _writeSnapshot(to, uint128(toBalance), uint128(toBalance.add(amount)));
              }
              // caching the aave governance address to avoid multiple state loads
              ITransferHook aaveGovernance = _aaveGovernance;
              if (aaveGovernance != ITransferHook(0)) {
                  aaveGovernance.onTransfer(from, to, amount);
              }
          }
      }// SPDX-License-Identifier: agpl-3.0
      pragma solidity 0.6.10;
      /**
       * @title VersionedInitializable
       *
       * @dev Helper contract to support initializer functions. To use it, replace
       * the constructor with a function that has the `initializer` modifier.
       * WARNING: Unlike constructors, initializer functions must be manually
       * invoked. This applies both to deploying an Initializable contract, as well
       * as extending an Initializable contract via inheritance.
       * WARNING: When used with inheritance, manual care must be taken to not invoke
       * a parent initializer twice, or ensure that all initializers are idempotent,
       * because this is not dealt with automatically as with constructors.
       *
       * @author Aave, inspired by the OpenZeppelin Initializable contract
       */
      abstract contract VersionedInitializable {
          /**
         * @dev Indicates that the contract has been initialized.
         */
          uint256 internal lastInitializedRevision = 0;
         /**
         * @dev Modifier to use in the initializer function of a contract.
         */
          modifier initializer() {
              uint256 revision = getRevision();
              require(revision > lastInitializedRevision, "Contract instance has already been initialized");
              lastInitializedRevision = revision;
              _;
          }
          /// @dev returns the revision number of the contract.
          /// Needs to be defined in the inherited class as a constant.
          function getRevision() internal pure virtual returns(uint256);
          // Reserved storage space to allow for layout changes in the future.
          uint256[50] private ______gap;
      }
      // SPDX-License-Identifier: agpl-3.0
      pragma solidity 0.6.10;
      import {IERC20} from "../interfaces/IERC20.sol";
      import {SafeMath} from "../open-zeppelin/SafeMath.sol";
      import {VersionedInitializable} from "../utils/VersionedInitializable.sol";
      /**
      * @title LendToAaveMigrator
      * @notice This contract implements the migration from LEND to AAVE token
      * @author Aave 
      */
      contract LendToAaveMigrator is VersionedInitializable {
          using SafeMath for uint256;
          IERC20 public immutable AAVE;
          IERC20 public immutable LEND;
          uint256 public immutable LEND_AAVE_RATIO;
          uint256 public constant REVISION = 1;
          
          uint256 public _totalLendMigrated;
          /**
          * @dev emitted on migration
          * @param sender the caller of the migration
          * @param amount the amount being migrated
          */
          event LendMigrated(address indexed sender, uint256 indexed amount);
          /**
          * @param aave the address of the AAVE token
          * @param lend the address of the LEND token
          * @param lendAaveRatio the exchange rate between LEND and AAVE 
           */
          constructor(IERC20 aave, IERC20 lend, uint256 lendAaveRatio) public {
              AAVE = aave;
              LEND = lend;
              LEND_AAVE_RATIO = lendAaveRatio;
          }
          /**
          * @dev initializes the implementation
          */
          function initialize() public initializer {
          }
          /**
          * @dev returns true if the migration started
          */
          function migrationStarted() external view returns(bool) {
              return lastInitializedRevision != 0;
          }
          /**
          * @dev executes the migration from LEND to AAVE. Users need to give allowance to this contract to transfer LEND before executing
          * this transaction.
          * @param amount the amount of LEND to be migrated
          */
          function migrateFromLEND(uint256 amount) external {
              require(lastInitializedRevision != 0, "MIGRATION_NOT_STARTED");
              _totalLendMigrated = _totalLendMigrated.add(amount);
              LEND.transferFrom(msg.sender, address(this), amount);
              AAVE.transfer(msg.sender, amount.div(LEND_AAVE_RATIO));
              emit LendMigrated(msg.sender, amount);
          }
          /**
          * @dev returns the implementation revision
          * @return the implementation revision
          */
          function getRevision() internal pure override returns (uint256) {
              return REVISION;
          }
      }// SPDX-License-Identifier: agpl-3.0
      pragma solidity 0.6.10;
      import "../interfaces/IERC20.sol";
      contract DoubleTransferHelper {
          IERC20 public immutable AAVE;
          constructor(IERC20 aave) public {
              AAVE = aave;
          }
          function doubleSend(address to, uint256 amount1, uint256 amount2) external {
              AAVE.transfer(to, amount1);
              AAVE.transfer(to, amount2);
          }
      }// SPDX-License-Identifier: agpl-3.0
      pragma solidity 0.6.10;
      import "../open-zeppelin/ERC20.sol";
      /**
       * @title ERC20Mintable
       * @dev ERC20 minting logic
       */
      contract MintableErc20 is ERC20 {
          constructor(string memory name, string memory symbol, uint8 decimals) ERC20(name, symbol) public {
              _setupDecimals(decimals);
          }
          /**
           * @dev Function to mint tokens
           * @param value The amount of tokens to mint.
           * @return A boolean that indicates if the operation was successful.
           */
          function mint(uint256 value) public returns (bool) {
              _mint(msg.sender, value);
              return true;
          }
      }
      // SPDX-License-Identifier: agpl-3.0
      pragma solidity 0.6.10;
      import {ITransferHook} from "../interfaces/ITransferHook.sol";
      contract MockTransferHook is ITransferHook {
          event MockHookEvent();
          function onTransfer(address from, address to, uint256 amount) external override {
              emit MockHookEvent();
          }
      }

      File 2 of 2: AaveTokenV3
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.0;
      import {BaseAaveTokenV2} from './BaseAaveTokenV2.sol';
      import {BaseDelegation} from './BaseDelegation.sol';
      contract AaveTokenV3 is BaseAaveTokenV2, BaseDelegation {
        /**
         * @dev initializes the contract upon assignment to the InitializableAdminUpgradeabilityProxy
         */
        function initialize() external virtual initializer {}
        function _afterTokenTransfer(
          address from,
          address to,
          uint256 fromBalanceBefore,
          uint256 toBalanceBefore,
          uint256 amount
        ) internal override {
          _delegationChangeOnTransfer(from, to, fromBalanceBefore, toBalanceBefore, amount);
        }
        function _getDelegationState(address user)
          internal
          view
          override
          returns (DelegationState memory)
        {
          DelegationAwareBalance memory userState = _balances[user];
          return
            DelegationState({
              delegatedPropositionBalance: userState.delegatedPropositionBalance,
              delegatedVotingBalance: userState.delegatedVotingBalance,
              delegationMode: userState.delegationMode
            });
        }
        function _getBalance(address user) internal view override returns (uint256) {
          return _balances[user].balance;
        }
        function _setDelegationState(address user, DelegationState memory delegationState)
          internal
          override
        {
          DelegationAwareBalance storage userState = _balances[user];
          userState.delegatedPropositionBalance = delegationState.delegatedPropositionBalance;
          userState.delegatedVotingBalance = delegationState.delegatedVotingBalance;
          userState.delegationMode = delegationState.delegationMode;
        }
        function _incrementNonces(address user) internal override returns (uint256) {
          unchecked {
            // Does not make sense to check because it's not realistic to reach uint256.max in nonce
            return _nonces[user]++;
          }
        }
        function _getDomainSeparator() internal view override returns (bytes32) {
          return DOMAIN_SEPARATOR();
        }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.0;
      import {ECDSA} from 'openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol';
      import {VersionedInitializable} from './utils/VersionedInitializable.sol';
      import {EIP712} from './utils/EIP712.sol';
      import {BaseAaveToken} from './BaseAaveToken.sol';
      abstract contract BaseAaveTokenV2 is BaseAaveToken, VersionedInitializable, EIP712 {
        /// @dev owner => next valid nonce to submit with permit()
        mapping(address => uint256) public _nonces;
        ///////// @dev DEPRECATED from AaveToken v1  //////////////////////////
        //////// kept for backwards compatibility with old storage layout ////
        uint256[3] private ______DEPRECATED_FROM_AAVE_V1;
        ///////// @dev END OF DEPRECATED from AaveToken v1  //////////////////////////
        // deprecated in favor to OZ EIP712
        bytes32 private __DEPRECATED_DOMAIN_SEPARATOR;
        ///////// @dev DEPRECATED from AaveToken v2  //////////////////////////
        //////// kept for backwards compatibility with old storage layout ////
        uint256[4] private ______DEPRECATED_FROM_AAVE_V2;
        ///////// @dev END OF DEPRECATED from AaveToken v2  //////////////////////////
        bytes32 public constant PERMIT_TYPEHASH =
          keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)');
        uint256 public constant REVISION = 4;
        constructor() EIP712('Aave token V3', '2') {}
        function DOMAIN_SEPARATOR() public view returns (bytes32) {
          return _domainSeparatorV4();
        }
        /**
         * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
         * @param owner the owner of the funds
         * @param spender the spender
         * @param value the amount
         * @param deadline the deadline timestamp, type(uint256).max for no deadline
         * @param v signature param
         * @param s signature param
         * @param r signature param
         */
        function permit(
          address owner,
          address spender,
          uint256 value,
          uint256 deadline,
          uint8 v,
          bytes32 r,
          bytes32 s
        ) external {
          require(owner != address(0), 'INVALID_OWNER');
          //solium-disable-next-line
          require(block.timestamp <= deadline, 'INVALID_EXPIRATION');
          uint256 currentValidNonce = _nonces[owner];
          bytes32 digest = _hashTypedDataV4(
            keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline))
          );
          require(owner == ECDSA.recover(digest, v, r, s), 'INVALID_SIGNATURE');
          unchecked {
            // does not make sense to check because it's not realistic to reach uint256.max in nonce
            _nonces[owner] = currentValidNonce + 1;
          }
          _approve(owner, spender, value);
        }
        /**
         * @dev returns the revision of the implementation contract
         */
        function getRevision() internal pure override returns (uint256) {
          return REVISION;
        }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.0;
      import {ECDSA} from 'openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol';
      import {SafeCast72} from './utils/SafeCast72.sol';
      import {IGovernancePowerDelegationToken} from './interfaces/IGovernancePowerDelegationToken.sol';
      import {DelegationMode} from './DelegationAwareBalance.sol';
      /**
       * @notice The contract implements generic delegation functionality for the upcoming governance v3
       * @author BGD Labs
       * @dev to make it's pluggable to any exising token it has a set of virtual functions
       *   for simple access to balances and permit functionality
       * @dev ************ IMPORTANT SECURITY CONSIDERATION ************
       *   current version of the token can be used only with asset which has 18 decimals
       *   and possible totalSupply lower then 4722366482869645213696,
       *   otherwise at least POWER_SCALE_FACTOR should be adjusted !!!
       *   *************************************************************
       */
      abstract contract BaseDelegation is IGovernancePowerDelegationToken {
        struct DelegationState {
          uint72 delegatedPropositionBalance;
          uint72 delegatedVotingBalance;
          DelegationMode delegationMode;
        }
        mapping(address => address) internal _votingDelegatee;
        mapping(address => address) internal _propositionDelegatee;
        /** @dev we assume that for the governance system delegation with 18 decimals of precision is not needed,
         *   by this constant we reduce it by 10, to 8 decimals.
         *   In case of Aave token this will allow to work with up to 47'223'664'828'696,45213696 total supply
         *   If your token already have less then 10 decimals, please change it to appropriate.
         */
        uint256 public constant POWER_SCALE_FACTOR = 1e10;
        bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH =
          keccak256(
            'DelegateByType(address delegator,address delegatee,uint8 delegationType,uint256 nonce,uint256 deadline)'
          );
        bytes32 public constant DELEGATE_TYPEHASH =
          keccak256('Delegate(address delegator,address delegatee,uint256 nonce,uint256 deadline)');
        /**
         * @notice returns eip-2612 compatible domain separator
         * @dev we expect that existing tokens, ie Aave, already have, so we want to reuse
         * @return domain separator
         */
        function _getDomainSeparator() internal view virtual returns (bytes32);
        /**
         * @notice gets the delegation state of a user
         * @param user address
         * @return state of a user's delegation
         */
        function _getDelegationState(address user) internal view virtual returns (DelegationState memory);
        /**
         * @notice returns the token balance of a user
         * @param user address
         * @return current nonce before increase
         */
        function _getBalance(address user) internal view virtual returns (uint256);
        /**
         * @notice increases and return the current nonce of a user
         * @dev should use `return nonce++;` pattern
         * @param user address
         * @return current nonce before increase
         */
        function _incrementNonces(address user) internal virtual returns (uint256);
        /**
         * @notice sets the delegation state of a user
         * @param user address
         * @param delegationState state of a user's delegation
         */
        function _setDelegationState(address user, DelegationState memory delegationState)
          internal
          virtual;
        /// @inheritdoc IGovernancePowerDelegationToken
        function delegateByType(address delegatee, GovernancePowerType delegationType)
          external
          virtual
          override
        {
          _delegateByType(msg.sender, delegatee, delegationType);
        }
        /// @inheritdoc IGovernancePowerDelegationToken
        function delegate(address delegatee) external override {
          _delegateByType(msg.sender, delegatee, GovernancePowerType.VOTING);
          _delegateByType(msg.sender, delegatee, GovernancePowerType.PROPOSITION);
        }
        /// @inheritdoc IGovernancePowerDelegationToken
        function getDelegateeByType(address delegator, GovernancePowerType delegationType)
          external
          view
          override
          returns (address)
        {
          return _getDelegateeByType(delegator, _getDelegationState(delegator), delegationType);
        }
        /// @inheritdoc IGovernancePowerDelegationToken
        function getDelegates(address delegator) external view override returns (address, address) {
          DelegationState memory delegatorBalance = _getDelegationState(delegator);
          return (
            _getDelegateeByType(delegator, delegatorBalance, GovernancePowerType.VOTING),
            _getDelegateeByType(delegator, delegatorBalance, GovernancePowerType.PROPOSITION)
          );
        }
        /// @inheritdoc IGovernancePowerDelegationToken
        function getPowerCurrent(address user, GovernancePowerType delegationType)
          public
          view
          virtual
          override
          returns (uint256)
        {
          DelegationState memory userState = _getDelegationState(user);
          uint256 userOwnPower = uint8(userState.delegationMode) & (uint8(delegationType) + 1) == 0
            ? _getBalance(user)
            : 0;
          uint256 userDelegatedPower = _getDelegatedPowerByType(userState, delegationType);
          return userOwnPower + userDelegatedPower;
        }
        /// @inheritdoc IGovernancePowerDelegationToken
        function getPowersCurrent(address user) external view override returns (uint256, uint256) {
          return (
            getPowerCurrent(user, GovernancePowerType.VOTING),
            getPowerCurrent(user, GovernancePowerType.PROPOSITION)
          );
        }
        /// @inheritdoc IGovernancePowerDelegationToken
        function metaDelegateByType(
          address delegator,
          address delegatee,
          GovernancePowerType delegationType,
          uint256 deadline,
          uint8 v,
          bytes32 r,
          bytes32 s
        ) external override {
          require(delegator != address(0), 'INVALID_OWNER');
          //solium-disable-next-line
          require(block.timestamp <= deadline, 'INVALID_EXPIRATION');
          bytes32 digest = ECDSA.toTypedDataHash(
            _getDomainSeparator(),
            keccak256(
              abi.encode(
                DELEGATE_BY_TYPE_TYPEHASH,
                delegator,
                delegatee,
                delegationType,
                _incrementNonces(delegator),
                deadline
              )
            )
          );
          require(delegator == ECDSA.recover(digest, v, r, s), 'INVALID_SIGNATURE');
          _delegateByType(delegator, delegatee, delegationType);
        }
        /// @inheritdoc IGovernancePowerDelegationToken
        function metaDelegate(
          address delegator,
          address delegatee,
          uint256 deadline,
          uint8 v,
          bytes32 r,
          bytes32 s
        ) external override {
          require(delegator != address(0), 'INVALID_OWNER');
          //solium-disable-next-line
          require(block.timestamp <= deadline, 'INVALID_EXPIRATION');
          bytes32 digest = ECDSA.toTypedDataHash(
            _getDomainSeparator(),
            keccak256(
              abi.encode(DELEGATE_TYPEHASH, delegator, delegatee, _incrementNonces(delegator), deadline)
            )
          );
          require(delegator == ECDSA.recover(digest, v, r, s), 'INVALID_SIGNATURE');
          _delegateByType(delegator, delegatee, GovernancePowerType.VOTING);
          _delegateByType(delegator, delegatee, GovernancePowerType.PROPOSITION);
        }
        /**
         * @dev Modifies the delegated power of a `delegatee` account by type (VOTING, PROPOSITION).
         * Passing the impact on the delegation of `delegatee` account before and after to reduce conditionals and not lose
         * any precision.
         * @param impactOnDelegationBefore how much impact a balance of another account had over the delegation of a `delegatee`
         * before an action.
         * For example, if the action is a delegation from one account to another, the impact before the action will be 0.
         * @param impactOnDelegationAfter how much impact a balance of another account will have  over the delegation of a `delegatee`
         * after an action.
         * For example, if the action is a delegation from one account to another, the impact after the action will be the whole balance
         * of the account changing the delegatee.
         * @param delegatee the user whom delegated governance power will be changed
         * @param delegationType the type of governance power delegation (VOTING, PROPOSITION)
         **/
        function _governancePowerTransferByType(
          uint256 impactOnDelegationBefore,
          uint256 impactOnDelegationAfter,
          address delegatee,
          GovernancePowerType delegationType
        ) internal {
          if (delegatee == address(0)) return;
          if (impactOnDelegationBefore == impactOnDelegationAfter) return;
          // we use uint72, because this is the most optimal for AaveTokenV3
          // To make delegated balance fit into uint72 we're decreasing precision of delegated balance by POWER_SCALE_FACTOR
          uint72 impactOnDelegationBefore72 = SafeCast72.toUint72(
            impactOnDelegationBefore / POWER_SCALE_FACTOR
          );
          uint72 impactOnDelegationAfter72 = SafeCast72.toUint72(
            impactOnDelegationAfter / POWER_SCALE_FACTOR
          );
          DelegationState memory delegateeState = _getDelegationState(delegatee);
          if (delegationType == GovernancePowerType.VOTING) {
            delegateeState.delegatedVotingBalance =
              delegateeState.delegatedVotingBalance -
              impactOnDelegationBefore72 +
              impactOnDelegationAfter72;
          } else {
            delegateeState.delegatedPropositionBalance =
              delegateeState.delegatedPropositionBalance -
              impactOnDelegationBefore72 +
              impactOnDelegationAfter72;
          }
          _setDelegationState(delegatee, delegateeState);
        }
        /**
         * @dev performs all state changes related delegation changes on transfer
         * @param from token sender
         * @param to token recipient
         * @param fromBalanceBefore balance of the sender before transfer
         * @param toBalanceBefore balance of the recipient before transfer
         * @param amount amount of tokens sent
         **/
        function _delegationChangeOnTransfer(
          address from,
          address to,
          uint256 fromBalanceBefore,
          uint256 toBalanceBefore,
          uint256 amount
        ) internal {
          if (from == to) {
            return;
          }
          if (from != address(0)) {
            DelegationState memory fromUserState = _getDelegationState(from);
            uint256 fromBalanceAfter = fromBalanceBefore - amount;
            if (fromUserState.delegationMode != DelegationMode.NO_DELEGATION) {
              _governancePowerTransferByType(
                fromBalanceBefore,
                fromBalanceAfter,
                _getDelegateeByType(from, fromUserState, GovernancePowerType.VOTING),
                GovernancePowerType.VOTING
              );
              _governancePowerTransferByType(
                fromBalanceBefore,
                fromBalanceAfter,
                _getDelegateeByType(from, fromUserState, GovernancePowerType.PROPOSITION),
                GovernancePowerType.PROPOSITION
              );
            }
          }
          if (to != address(0)) {
            DelegationState memory toUserState = _getDelegationState(to);
            uint256 toBalanceAfter = toBalanceBefore + amount;
            if (toUserState.delegationMode != DelegationMode.NO_DELEGATION) {
              _governancePowerTransferByType(
                toBalanceBefore,
                toBalanceAfter,
                _getDelegateeByType(to, toUserState, GovernancePowerType.VOTING),
                GovernancePowerType.VOTING
              );
              _governancePowerTransferByType(
                toBalanceBefore,
                toBalanceAfter,
                _getDelegateeByType(to, toUserState, GovernancePowerType.PROPOSITION),
                GovernancePowerType.PROPOSITION
              );
            }
          }
        }
        /**
         * @dev Extracts from state and returns delegated governance power (Voting, Proposition)
         * @param userState the current state of a user
         * @param delegationType the type of governance power delegation (VOTING, PROPOSITION)
         **/
        function _getDelegatedPowerByType(
          DelegationState memory userState,
          GovernancePowerType delegationType
        ) internal pure returns (uint256) {
          return
            POWER_SCALE_FACTOR *
            (
              delegationType == GovernancePowerType.VOTING
                ? userState.delegatedVotingBalance
                : userState.delegatedPropositionBalance
            );
        }
        /**
         * @dev Extracts from state and returns the delegatee of a delegator by type of governance power (Voting, Proposition)
         * - If the delegator doesn't have any delegatee, returns address(0)
         * @param delegator delegator
         * @param userState the current state of a user
         * @param delegationType the type of governance power delegation (VOTING, PROPOSITION)
         **/
        function _getDelegateeByType(
          address delegator,
          DelegationState memory userState,
          GovernancePowerType delegationType
        ) internal view returns (address) {
          if (delegationType == GovernancePowerType.VOTING) {
            return
              /// With the & operation, we cover both VOTING_DELEGATED delegation and FULL_POWER_DELEGATED
              /// as VOTING_DELEGATED is equivalent to 01 in binary and FULL_POWER_DELEGATED is equivalent to 11
              (uint8(userState.delegationMode) & uint8(DelegationMode.VOTING_DELEGATED)) != 0
                ? _votingDelegatee[delegator]
                : address(0);
          }
          return
            userState.delegationMode >= DelegationMode.PROPOSITION_DELEGATED
              ? _propositionDelegatee[delegator]
              : address(0);
        }
        /**
         * @dev Changes user's delegatee address by type of governance power (Voting, Proposition)
         * @param delegator delegator
         * @param delegationType the type of governance power delegation (VOTING, PROPOSITION)
         * @param _newDelegatee the new delegatee
         **/
        function _updateDelegateeByType(
          address delegator,
          GovernancePowerType delegationType,
          address _newDelegatee
        ) internal {
          address newDelegatee = _newDelegatee == delegator ? address(0) : _newDelegatee;
          if (delegationType == GovernancePowerType.VOTING) {
            _votingDelegatee[delegator] = newDelegatee;
          } else {
            _propositionDelegatee[delegator] = newDelegatee;
          }
        }
        /**
         * @dev Updates the specific flag which signaling about existence of delegation of governance power (Voting, Proposition)
         * @param userState a user state to change
         * @param delegationType the type of governance power delegation (VOTING, PROPOSITION)
         * @param willDelegate next state of delegation
         **/
        function _updateDelegationModeByType(
          DelegationState memory userState,
          GovernancePowerType delegationType,
          bool willDelegate
        ) internal pure returns (DelegationState memory) {
          if (willDelegate) {
            // Because GovernancePowerType starts from 0, we should add 1 first, then we apply bitwise OR
            userState.delegationMode = DelegationMode(
              uint8(userState.delegationMode) | (uint8(delegationType) + 1)
            );
          } else {
            // First bitwise NEGATION, ie was 01, after XOR with 11 will be 10,
            // then bitwise AND, which means it will keep only another delegation type if it exists
            userState.delegationMode = DelegationMode(
              uint8(userState.delegationMode) &
                ((uint8(delegationType) + 1) ^ uint8(DelegationMode.FULL_POWER_DELEGATED))
            );
          }
          return userState;
        }
        /**
         * @dev This is the equivalent of an ERC20 transfer(), but for a power type: an atomic transfer of a balance (power).
         * When needed, it decreases the power of the `delegator` and when needed, it increases the power of the `delegatee`
         * @param delegator delegator
         * @param _delegatee the user which delegated power will change
         * @param delegationType the type of delegation (VOTING, PROPOSITION)
         **/
        function _delegateByType(
          address delegator,
          address _delegatee,
          GovernancePowerType delegationType
        ) internal {
          // Here we unify the property that delegating power to address(0) == delegating power to yourself == no delegation
          // So from now on, not being delegating is (exclusively) that delegatee == address(0)
          address delegatee = _delegatee == delegator ? address(0) : _delegatee;
          // We read the whole struct before validating delegatee, because in the optimistic case
          // (_delegatee != currentDelegatee) we will reuse userState in the rest of the function
          DelegationState memory delegatorState = _getDelegationState(delegator);
          address currentDelegatee = _getDelegateeByType(delegator, delegatorState, delegationType);
          if (delegatee == currentDelegatee) return;
          bool delegatingNow = currentDelegatee != address(0);
          bool willDelegateAfter = delegatee != address(0);
          uint256 delegatorBalance = _getBalance(delegator);
          if (delegatingNow) {
            _governancePowerTransferByType(delegatorBalance, 0, currentDelegatee, delegationType);
          }
          if (willDelegateAfter) {
            _governancePowerTransferByType(0, delegatorBalance, delegatee, delegationType);
          }
          _updateDelegateeByType(delegator, delegationType, delegatee);
          if (willDelegateAfter != delegatingNow) {
            _setDelegationState(
              delegator,
              _updateDelegationModeByType(delegatorState, delegationType, willDelegateAfter)
            );
          }
          emit DelegateChanged(delegator, delegatee, delegationType);
        }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
      pragma solidity ^0.8.0;
      import "../Strings.sol";
      /**
       * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
       *
       * These functions can be used to verify that a message was signed by the holder
       * of the private keys of a given address.
       */
      library ECDSA {
          enum RecoverError {
              NoError,
              InvalidSignature,
              InvalidSignatureLength,
              InvalidSignatureS,
              InvalidSignatureV // Deprecated in v4.8
          }
          function _throwError(RecoverError error) private pure {
              if (error == RecoverError.NoError) {
                  return; // no error: do nothing
              } else if (error == RecoverError.InvalidSignature) {
                  revert("ECDSA: invalid signature");
              } else if (error == RecoverError.InvalidSignatureLength) {
                  revert("ECDSA: invalid signature length");
              } else if (error == RecoverError.InvalidSignatureS) {
                  revert("ECDSA: invalid signature 's' value");
              }
          }
          /**
           * @dev Returns the address that signed a hashed message (`hash`) with
           * `signature` or error string. This address can then be used for verification purposes.
           *
           * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
           * this function rejects them by requiring the `s` value to be in the lower
           * half order, and the `v` value to be either 27 or 28.
           *
           * IMPORTANT: `hash` _must_ be the result of a hash operation for the
           * verification to be secure: it is possible to craft signatures that
           * recover to arbitrary addresses for non-hashed data. A safe way to ensure
           * this is by receiving a hash of the original message (which may otherwise
           * be too long), and then calling {toEthSignedMessageHash} on it.
           *
           * Documentation for signature generation:
           * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
           * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
           *
           * _Available since v4.3._
           */
          function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
              if (signature.length == 65) {
                  bytes32 r;
                  bytes32 s;
                  uint8 v;
                  // ecrecover takes the signature parameters, and the only way to get them
                  // currently is to use assembly.
                  /// @solidity memory-safe-assembly
                  assembly {
                      r := mload(add(signature, 0x20))
                      s := mload(add(signature, 0x40))
                      v := byte(0, mload(add(signature, 0x60)))
                  }
                  return tryRecover(hash, v, r, s);
              } else {
                  return (address(0), RecoverError.InvalidSignatureLength);
              }
          }
          /**
           * @dev Returns the address that signed a hashed message (`hash`) with
           * `signature`. This address can then be used for verification purposes.
           *
           * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
           * this function rejects them by requiring the `s` value to be in the lower
           * half order, and the `v` value to be either 27 or 28.
           *
           * IMPORTANT: `hash` _must_ be the result of a hash operation for the
           * verification to be secure: it is possible to craft signatures that
           * recover to arbitrary addresses for non-hashed data. A safe way to ensure
           * this is by receiving a hash of the original message (which may otherwise
           * be too long), and then calling {toEthSignedMessageHash} on it.
           */
          function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
              (address recovered, RecoverError error) = tryRecover(hash, signature);
              _throwError(error);
              return recovered;
          }
          /**
           * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
           *
           * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
           *
           * _Available since v4.3._
           */
          function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
              bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
              uint8 v = uint8((uint256(vs) >> 255) + 27);
              return tryRecover(hash, v, r, s);
          }
          /**
           * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
           *
           * _Available since v4.2._
           */
          function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
              (address recovered, RecoverError error) = tryRecover(hash, r, vs);
              _throwError(error);
              return recovered;
          }
          /**
           * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
           * `r` and `s` signature fields separately.
           *
           * _Available since v4.3._
           */
          function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
              // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
              // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
              // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
              // signatures from current libraries generate a unique signature with an s-value in the lower half order.
              //
              // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
              // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
              // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
              // these malleable signatures as well.
              if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                  return (address(0), RecoverError.InvalidSignatureS);
              }
              // If the signature is valid (and not malleable), return the signer address
              address signer = ecrecover(hash, v, r, s);
              if (signer == address(0)) {
                  return (address(0), RecoverError.InvalidSignature);
              }
              return (signer, RecoverError.NoError);
          }
          /**
           * @dev Overload of {ECDSA-recover} that receives the `v`,
           * `r` and `s` signature fields separately.
           */
          function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
              (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
              _throwError(error);
              return recovered;
          }
          /**
           * @dev Returns an Ethereum Signed Message, created from a `hash`. This
           * produces hash corresponding to the one signed with the
           * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
           * JSON-RPC method as part of EIP-191.
           *
           * See {recover}.
           */
          function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
              // 32 is the length in bytes of hash,
              // enforced by the type signature above
              /// @solidity memory-safe-assembly
              assembly {
                  mstore(0x00, "\\x19Ethereum Signed Message:\
      32")
                  mstore(0x1c, hash)
                  message := keccak256(0x00, 0x3c)
              }
          }
          /**
           * @dev Returns an Ethereum Signed Message, created from `s`. This
           * produces hash corresponding to the one signed with the
           * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
           * JSON-RPC method as part of EIP-191.
           *
           * See {recover}.
           */
          function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
              return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
      ", Strings.toString(s.length), s));
          }
          /**
           * @dev Returns an Ethereum Signed Typed Data, created from a
           * `domainSeparator` and a `structHash`. This produces hash corresponding
           * to the one signed with the
           * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
           * JSON-RPC method as part of EIP-712.
           *
           * See {recover}.
           */
          function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
              /// @solidity memory-safe-assembly
              assembly {
                  let ptr := mload(0x40)
                  mstore(ptr, "\\x19\\x01")
                  mstore(add(ptr, 0x02), domainSeparator)
                  mstore(add(ptr, 0x22), structHash)
                  data := keccak256(ptr, 0x42)
              }
          }
          /**
           * @dev Returns an Ethereum Signed Data with intended validator, created from a
           * `validator` and `data` according to the version 0 of EIP-191.
           *
           * See {recover}.
           */
          function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
              return keccak256(abi.encodePacked("\\x19\\x00", validator, data));
          }
      }
      // SPDX-License-Identifier: agpl-3.0
      pragma solidity ^0.8.0;
      /**
       * @title VersionedInitializable
       *
       * @dev Helper contract to support initializer functions. To use it, replace
       * the constructor with a function that has the `initializer` modifier.
       * WARNING: Unlike constructors, initializer functions must be manually
       * invoked. This applies both to deploying an Initializable contract, as well
       * as extending an Initializable contract via inheritance.
       * WARNING: When used with inheritance, manual care must be taken to not invoke
       * a parent initializer twice, or ensure that all initializers are idempotent,
       * because this is not dealt with automatically as with constructors.
       *
       * @author Aave, inspired by the OpenZeppelin Initializable contract
       */
      abstract contract VersionedInitializable {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint256 internal lastInitializedRevision = 0;
        /**
         * @dev Modifier to use in the initializer function of a contract.
         */
        modifier initializer() {
          uint256 revision = getRevision();
          require(revision > lastInitializedRevision, 'Contract instance has already been initialized');
          lastInitializedRevision = revision;
          _;
        }
        /// @dev returns the revision number of the contract.
        /// Needs to be defined in the inherited class as a constant.
        function getRevision() internal pure virtual returns (uint256);
        // Reserved storage space to allow for layout changes in the future.
        uint256[50] private ______gap;
      }
      // SPDX-License-Identifier: MIT
      // Contract modified from OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol) to remove local
      // fallback storage variables, so contract does not affect on existing storage layout. This works as its used on contracts
      // that have name and revision < 32 bytes
      pragma solidity ^0.8.10;
      import {ECDSA} from 'openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol';
      import {ShortStrings, ShortString} from 'openzeppelin-contracts/contracts/utils/ShortStrings.sol';
      import {IERC5267} from 'openzeppelin-contracts/contracts/interfaces/IERC5267.sol';
      /**
       * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
       *
       * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
       * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
       * they need in their contracts using a combination of `abi.encode` and `keccak256`.
       *
       * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
       * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
       * ({_hashTypedDataV4}).
       *
       * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
       * the chain id to protect against replay attacks on an eventual fork of the chain.
       *
       * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
       * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
       *
       * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
       * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
       * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
       *
       * _Available since v3.4._
       *
       * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
       */
      abstract contract EIP712 is IERC5267 {
        using ShortStrings for *;
        bytes32 private constant _TYPE_HASH =
          keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)');
        // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
        // invalidate the cached domain separator if the chain id changes.
        bytes32 private immutable _cachedDomainSeparator;
        uint256 private immutable _cachedChainId;
        address private immutable _cachedThis;
        bytes32 private immutable _hashedName;
        bytes32 private immutable _hashedVersion;
        ShortString private immutable _name;
        ShortString private immutable _version;
        /**
         * @dev Initializes the domain separator and parameter caches.
         *
         * The meaning of `name` and `version` is specified in
         * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
         *
         * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
         * - `version`: the current major version of the signing domain.
         *
         * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
         * contract upgrade].
         */
        /// @dev BGD: removed usage of fallback variables to not modify previous storage layout. As we know that the length of
        ///           name and version will not be bigger than 32 bytes we use toShortString as there is no need to use the fallback system.
        constructor(string memory name, string memory version) {
          _name = name.toShortString();
          _version = version.toShortString();
          _hashedName = keccak256(bytes(name));
          _hashedVersion = keccak256(bytes(version));
          _cachedChainId = block.chainid;
          _cachedDomainSeparator = _buildDomainSeparator();
          _cachedThis = address(this);
        }
        /**
         * @dev Returns the domain separator for the current chain.
         */
        function _domainSeparatorV4() internal view returns (bytes32) {
          if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
            return _cachedDomainSeparator;
          } else {
            return _buildDomainSeparator();
          }
        }
        function _buildDomainSeparator() private view returns (bytes32) {
          return
            keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
        }
        /**
         * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
         * function returns the hash of the fully encoded EIP712 message for this domain.
         *
         * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
         *
         * ```solidity
         * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
         *     keccak256("Mail(address to,string contents)"),
         *     mailTo,
         *     keccak256(bytes(mailContents))
         * )));
         * address signer = ECDSA.recover(digest, signature);
         * ```
         */
        function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
          return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
        }
        /**
         * @dev See {EIP-5267}.
         *
         * _Available since v4.9._
         */
        function eip712Domain()
          public
          view
          virtual
          returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
          )
        {
          return (
            hex'0f', // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
          );
        }
        /**
         * @dev The name parameter for the EIP712 domain.
         *
         * NOTE: By default this function reads _name which is an immutable value.
         * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
         *
         * _Available since v5.0._
         */
        /// @dev BGD: we use toString instead of toStringWithFallback as we dont have fallback, to not modify previous storage layout
        // solhint-disable-next-line func-name-mixedcase
        function _EIP712Name() internal view returns (string memory) {
          return _name.toString(); // _name.toStringWithFallback(_nameFallback);
        }
        /**
         * @dev The version parameter for the EIP712 domain.
         *
         * NOTE: By default this function reads _version which is an immutable value.
         * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
         *
         * _Available since v5.0._
         */
        /// @dev BGD: we use toString instead of toStringWithFallback as we dont have fallback, to not modify previous storage layout
        // solhint-disable-next-line func-name-mixedcase
        function _EIP712Version() internal view returns (string memory) {
          return _version.toString();
        }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.0;
      import {Context} from 'openzeppelin-contracts/contracts/utils/Context.sol';
      import {IERC20} from 'openzeppelin-contracts/contracts/token/ERC20/IERC20.sol';
      import {IERC20Metadata} from 'openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol';
      import {DelegationMode} from './DelegationAwareBalance.sol';
      // Inspired by OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
      abstract contract BaseAaveToken is Context, IERC20Metadata {
        struct DelegationAwareBalance {
          uint104 balance;
          uint72 delegatedPropositionBalance;
          uint72 delegatedVotingBalance;
          DelegationMode delegationMode;
        }
        mapping(address => DelegationAwareBalance) internal _balances;
        mapping(address => mapping(address => uint256)) internal _allowances;
        uint256 internal _totalSupply;
        string internal _name;
        string internal _symbol;
        // @dev DEPRECATED
        // kept for backwards compatibility with old storage layout
        uint8 private ______DEPRECATED_OLD_ERC20_DECIMALS;
        /**
         * @dev Returns the name of the token.
         */
        function name() public view virtual override returns (string memory) {
          return _name;
        }
        /**
         * @dev Returns the symbol of the token, usually a shorter version of the
         * name.
         */
        function symbol() public view virtual override returns (string memory) {
          return _symbol;
        }
        function decimals() public view virtual override returns (uint8) {
          return 18;
        }
        function totalSupply() public view virtual override returns (uint256) {
          return _totalSupply;
        }
        function balanceOf(address account) public view virtual override returns (uint256) {
          return _balances[account].balance;
        }
        function transfer(address to, uint256 amount) public virtual override returns (bool) {
          address owner = _msgSender();
          _transfer(owner, to, amount);
          return true;
        }
        function allowance(address owner, address spender)
          public
          view
          virtual
          override
          returns (uint256)
        {
          return _allowances[owner][spender];
        }
        function approve(address spender, uint256 amount) public virtual override returns (bool) {
          address owner = _msgSender();
          _approve(owner, spender, amount);
          return true;
        }
        function transferFrom(
          address from,
          address to,
          uint256 amount
        ) public virtual override returns (bool) {
          address spender = _msgSender();
          _spendAllowance(from, spender, amount);
          _transfer(from, to, amount);
          return true;
        }
        function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
          address owner = _msgSender();
          _approve(owner, spender, _allowances[owner][spender] + addedValue);
          return true;
        }
        function decreaseAllowance(address spender, uint256 subtractedValue)
          public
          virtual
          returns (bool)
        {
          address owner = _msgSender();
          uint256 currentAllowance = _allowances[owner][spender];
          require(currentAllowance >= subtractedValue, 'ERC20: decreased allowance below zero');
          unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
          }
          return true;
        }
        function _transfer(
          address from,
          address to,
          uint256 amount
        ) internal virtual {
          require(from != address(0), 'ERC20: transfer from the zero address');
          require(to != address(0), 'ERC20: transfer to the zero address');
          if (from != to) {
            uint104 fromBalanceBefore = _balances[from].balance;
            uint104 toBalanceBefore = _balances[to].balance;
            require(fromBalanceBefore >= amount, 'ERC20: transfer amount exceeds balance');
            unchecked {
              _balances[from].balance = fromBalanceBefore - uint104(amount);
            }
            _balances[to].balance = toBalanceBefore + uint104(amount);
            _afterTokenTransfer(from, to, fromBalanceBefore, toBalanceBefore, amount);
          }
          emit Transfer(from, to, amount);
        }
        function _approve(
          address owner,
          address spender,
          uint256 amount
        ) internal virtual {
          require(owner != address(0), 'ERC20: approve from the zero address');
          require(spender != address(0), 'ERC20: approve to the zero address');
          _allowances[owner][spender] = amount;
          emit Approval(owner, spender, amount);
        }
        function _spendAllowance(
          address owner,
          address spender,
          uint256 amount
        ) internal virtual {
          uint256 currentAllowance = allowance(owner, spender);
          if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, 'ERC20: insufficient allowance');
            unchecked {
              _approve(owner, spender, currentAllowance - amount);
            }
          }
        }
        /**
         * @dev after token transfer hook, added for delegation system
         * @param from token sender
         * @param to token recipient
         * @param fromBalanceBefore balance of the sender before transfer
         * @param toBalanceBefore balance of the recipient before transfer
         * @param amount amount of tokens sent
         **/
        function _afterTokenTransfer(
          address from,
          address to,
          uint256 fromBalanceBefore,
          uint256 toBalanceBefore,
          uint256 amount
        ) internal virtual {}
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.0;
      /** @notice influenced by OpenZeppelin SafeCast lib, which is missing to uint72 cast
       * @author BGD Labs
       */
      library SafeCast72 {
        /**
         * @dev Returns the downcasted uint72 from uint256, reverting on
         * overflow (when the input is greater than largest uint72).
         *
         * Counterpart to Solidity's `uint16` operator.
         *
         * Requirements:
         *
         * - input must fit into 72 bits
         */
        function toUint72(uint256 value) internal pure returns (uint72) {
          require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
          return uint72(value);
        }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.0;
      interface IGovernancePowerDelegationToken {
        enum GovernancePowerType {
          VOTING,
          PROPOSITION
        }
        /**
         * @dev emitted when a user delegates to another
         * @param delegator the user which delegated governance power
         * @param delegatee the delegatee
         * @param delegationType the type of delegation (VOTING, PROPOSITION)
         **/
        event DelegateChanged(
          address indexed delegator,
          address indexed delegatee,
          GovernancePowerType delegationType
        );
        // @dev we removed DelegatedPowerChanged event because to reconstruct the full state of the system,
        // is enough to have Transfer and DelegateChanged TODO: document it
        /**
         * @dev delegates the specific power to a delegatee
         * @param delegatee the user which delegated power will change
         * @param delegationType the type of delegation (VOTING, PROPOSITION)
         **/
        function delegateByType(address delegatee, GovernancePowerType delegationType) external;
        /**
         * @dev delegates all the governance powers to a specific user
         * @param delegatee the user to which the powers will be delegated
         **/
        function delegate(address delegatee) external;
        /**
         * @dev returns the delegatee of an user
         * @param delegator the address of the delegator
         * @param delegationType the type of delegation (VOTING, PROPOSITION)
         * @return address of the specified delegatee
         **/
        function getDelegateeByType(address delegator, GovernancePowerType delegationType)
          external
          view
          returns (address);
        /**
         * @dev returns delegates of an user
         * @param delegator the address of the delegator
         * @return a tuple of addresses the VOTING and PROPOSITION delegatee
         **/
        function getDelegates(address delegator)
          external
          view
          returns (address, address);
        /**
         * @dev returns the current voting or proposition power of a user.
         * @param user the user
         * @param delegationType the type of delegation (VOTING, PROPOSITION)
         * @return the current voting or proposition power of a user
         **/
        function getPowerCurrent(address user, GovernancePowerType delegationType)
          external
          view
          returns (uint256);
        /**
         * @dev returns the current voting or proposition power of a user.
         * @param user the user
         * @return the current voting and proposition power of a user
         **/
        function getPowersCurrent(address user)
          external
          view
          returns (uint256, uint256);
        /**
         * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
         * @param delegator the owner of the funds
         * @param delegatee the user to who owner delegates his governance power
         * @param delegationType the type of governance power delegation (VOTING, PROPOSITION)
         * @param deadline the deadline timestamp, type(uint256).max for no deadline
         * @param v signature param
         * @param s signature param
         * @param r signature param
         */
        function metaDelegateByType(
          address delegator,
          address delegatee,
          GovernancePowerType delegationType,
          uint256 deadline,
          uint8 v,
          bytes32 r,
          bytes32 s
        ) external;
        /**
         * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
         * @param delegator the owner of the funds
         * @param delegatee the user to who delegator delegates his voting and proposition governance power
         * @param deadline the deadline timestamp, type(uint256).max for no deadline
         * @param v signature param
         * @param s signature param
         * @param r signature param
         */
        function metaDelegate(
          address delegator,
          address delegatee,
          uint256 deadline,
          uint8 v,
          bytes32 r,
          bytes32 s
        ) external;
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.0;
      enum DelegationMode {
        NO_DELEGATION,
        VOTING_DELEGATED,
        PROPOSITION_DELEGATED,
        FULL_POWER_DELEGATED
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
      pragma solidity ^0.8.0;
      import "./math/Math.sol";
      import "./math/SignedMath.sol";
      /**
       * @dev String operations.
       */
      library Strings {
          bytes16 private constant _SYMBOLS = "0123456789abcdef";
          uint8 private constant _ADDRESS_LENGTH = 20;
          /**
           * @dev Converts a `uint256` to its ASCII `string` decimal representation.
           */
          function toString(uint256 value) internal pure returns (string memory) {
              unchecked {
                  uint256 length = Math.log10(value) + 1;
                  string memory buffer = new string(length);
                  uint256 ptr;
                  /// @solidity memory-safe-assembly
                  assembly {
                      ptr := add(buffer, add(32, length))
                  }
                  while (true) {
                      ptr--;
                      /// @solidity memory-safe-assembly
                      assembly {
                          mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                      }
                      value /= 10;
                      if (value == 0) break;
                  }
                  return buffer;
              }
          }
          /**
           * @dev Converts a `int256` to its ASCII `string` decimal representation.
           */
          function toString(int256 value) internal pure returns (string memory) {
              return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
          }
          /**
           * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
           */
          function toHexString(uint256 value) internal pure returns (string memory) {
              unchecked {
                  return toHexString(value, Math.log256(value) + 1);
              }
          }
          /**
           * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
           */
          function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
              bytes memory buffer = new bytes(2 * length + 2);
              buffer[0] = "0";
              buffer[1] = "x";
              for (uint256 i = 2 * length + 1; i > 1; --i) {
                  buffer[i] = _SYMBOLS[value & 0xf];
                  value >>= 4;
              }
              require(value == 0, "Strings: hex length insufficient");
              return string(buffer);
          }
          /**
           * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
           */
          function toHexString(address addr) internal pure returns (string memory) {
              return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
          }
          /**
           * @dev Returns true if the two strings are equal.
           */
          function equal(string memory a, string memory b) internal pure returns (bool) {
              return keccak256(bytes(a)) == keccak256(bytes(b));
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)
      pragma solidity ^0.8.8;
      import "./StorageSlot.sol";
      // | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
      // | length  | 0x                                                              BB |
      type ShortString is bytes32;
      /**
       * @dev This library provides functions to convert short memory strings
       * into a `ShortString` type that can be used as an immutable variable.
       *
       * Strings of arbitrary length can be optimized using this library if
       * they are short enough (up to 31 bytes) by packing them with their
       * length (1 byte) in a single EVM word (32 bytes). Additionally, a
       * fallback mechanism can be used for every other case.
       *
       * Usage example:
       *
       * ```solidity
       * contract Named {
       *     using ShortStrings for *;
       *
       *     ShortString private immutable _name;
       *     string private _nameFallback;
       *
       *     constructor(string memory contractName) {
       *         _name = contractName.toShortStringWithFallback(_nameFallback);
       *     }
       *
       *     function name() external view returns (string memory) {
       *         return _name.toStringWithFallback(_nameFallback);
       *     }
       * }
       * ```
       */
      library ShortStrings {
          // Used as an identifier for strings longer than 31 bytes.
          bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
          error StringTooLong(string str);
          error InvalidShortString();
          /**
           * @dev Encode a string of at most 31 chars into a `ShortString`.
           *
           * This will trigger a `StringTooLong` error is the input string is too long.
           */
          function toShortString(string memory str) internal pure returns (ShortString) {
              bytes memory bstr = bytes(str);
              if (bstr.length > 31) {
                  revert StringTooLong(str);
              }
              return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
          }
          /**
           * @dev Decode a `ShortString` back to a "normal" string.
           */
          function toString(ShortString sstr) internal pure returns (string memory) {
              uint256 len = byteLength(sstr);
              // using `new string(len)` would work locally but is not memory safe.
              string memory str = new string(32);
              /// @solidity memory-safe-assembly
              assembly {
                  mstore(str, len)
                  mstore(add(str, 0x20), sstr)
              }
              return str;
          }
          /**
           * @dev Return the length of a `ShortString`.
           */
          function byteLength(ShortString sstr) internal pure returns (uint256) {
              uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
              if (result > 31) {
                  revert InvalidShortString();
              }
              return result;
          }
          /**
           * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
           */
          function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
              if (bytes(value).length < 32) {
                  return toShortString(value);
              } else {
                  StorageSlot.getStringSlot(store).value = value;
                  return ShortString.wrap(_FALLBACK_SENTINEL);
              }
          }
          /**
           * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
           */
          function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
              if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
                  return toString(value);
              } else {
                  return store;
              }
          }
          /**
           * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
           *
           * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
           * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
           */
          function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
              if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
                  return byteLength(value);
              } else {
                  return bytes(store).length;
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)
      pragma solidity ^0.8.0;
      interface IERC5267 {
          /**
           * @dev MAY be emitted to signal that the domain could have changed.
           */
          event EIP712DomainChanged();
          /**
           * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
           * signature.
           */
          function eip712Domain()
              external
              view
              returns (
                  bytes1 fields,
                  string memory name,
                  string memory version,
                  uint256 chainId,
                  address verifyingContract,
                  bytes32 salt,
                  uint256[] memory extensions
              );
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Provides information about the current execution context, including the
       * sender of the transaction and its data. While these are generally available
       * via msg.sender and msg.data, they should not be accessed in such a direct
       * manner, since when dealing with meta-transactions the account sending and
       * paying for execution may not be the actual sender (as far as an application
       * is concerned).
       *
       * This contract is only required for intermediate, library-like contracts.
       */
      abstract contract Context {
          function _msgSender() internal view virtual returns (address) {
              return msg.sender;
          }
          function _msgData() internal view virtual returns (bytes calldata) {
              return msg.data;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC20 standard as defined in the EIP.
       */
      interface IERC20 {
          /**
           * @dev Emitted when `value` tokens are moved from one account (`from`) to
           * another (`to`).
           *
           * Note that `value` may be zero.
           */
          event Transfer(address indexed from, address indexed to, uint256 value);
          /**
           * @dev Emitted when the allowance of a `spender` for an `owner` is set by
           * a call to {approve}. `value` is the new allowance.
           */
          event Approval(address indexed owner, address indexed spender, uint256 value);
          /**
           * @dev Returns the amount of tokens in existence.
           */
          function totalSupply() external view returns (uint256);
          /**
           * @dev Returns the amount of tokens owned by `account`.
           */
          function balanceOf(address account) external view returns (uint256);
          /**
           * @dev Moves `amount` tokens from the caller's account to `to`.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * Emits a {Transfer} event.
           */
          function transfer(address to, uint256 amount) external returns (bool);
          /**
           * @dev Returns the remaining number of tokens that `spender` will be
           * allowed to spend on behalf of `owner` through {transferFrom}. This is
           * zero by default.
           *
           * This value changes when {approve} or {transferFrom} are called.
           */
          function allowance(address owner, address spender) external view returns (uint256);
          /**
           * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * IMPORTANT: Beware that changing an allowance with this method brings the risk
           * that someone may use both the old and the new allowance by unfortunate
           * transaction ordering. One possible solution to mitigate this race
           * condition is to first reduce the spender's allowance to 0 and set the
           * desired value afterwards:
           * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
           *
           * Emits an {Approval} event.
           */
          function approve(address spender, uint256 amount) external returns (bool);
          /**
           * @dev Moves `amount` tokens from `from` to `to` using the
           * allowance mechanism. `amount` is then deducted from the caller's
           * allowance.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * Emits a {Transfer} event.
           */
          function transferFrom(address from, address to, uint256 amount) external returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
      pragma solidity ^0.8.0;
      import "../IERC20.sol";
      /**
       * @dev Interface for the optional metadata functions from the ERC20 standard.
       *
       * _Available since v4.1._
       */
      interface IERC20Metadata is IERC20 {
          /**
           * @dev Returns the name of the token.
           */
          function name() external view returns (string memory);
          /**
           * @dev Returns the symbol of the token.
           */
          function symbol() external view returns (string memory);
          /**
           * @dev Returns the decimals places of the token.
           */
          function decimals() external view returns (uint8);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Standard math utilities missing in the Solidity language.
       */
      library Math {
          enum Rounding {
              Down, // Toward negative infinity
              Up, // Toward infinity
              Zero // Toward zero
          }
          /**
           * @dev Returns the largest of two numbers.
           */
          function max(uint256 a, uint256 b) internal pure returns (uint256) {
              return a > b ? a : b;
          }
          /**
           * @dev Returns the smallest of two numbers.
           */
          function min(uint256 a, uint256 b) internal pure returns (uint256) {
              return a < b ? a : b;
          }
          /**
           * @dev Returns the average of two numbers. The result is rounded towards
           * zero.
           */
          function average(uint256 a, uint256 b) internal pure returns (uint256) {
              // (a + b) / 2 can overflow.
              return (a & b) + (a ^ b) / 2;
          }
          /**
           * @dev Returns the ceiling of the division of two numbers.
           *
           * This differs from standard division with `/` in that it rounds up instead
           * of rounding down.
           */
          function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
              // (a + b - 1) / b can overflow on addition, so we distribute.
              return a == 0 ? 0 : (a - 1) / b + 1;
          }
          /**
           * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
           * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
           * with further edits by Uniswap Labs also under MIT license.
           */
          function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
              unchecked {
                  // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                  // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                  // variables such that product = prod1 * 2^256 + prod0.
                  uint256 prod0; // Least significant 256 bits of the product
                  uint256 prod1; // Most significant 256 bits of the product
                  assembly {
                      let mm := mulmod(x, y, not(0))
                      prod0 := mul(x, y)
                      prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                  }
                  // Handle non-overflow cases, 256 by 256 division.
                  if (prod1 == 0) {
                      // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                      // The surrounding unchecked block does not change this fact.
                      // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                      return prod0 / denominator;
                  }
                  // Make sure the result is less than 2^256. Also prevents denominator == 0.
                  require(denominator > prod1, "Math: mulDiv overflow");
                  ///////////////////////////////////////////////
                  // 512 by 256 division.
                  ///////////////////////////////////////////////
                  // Make division exact by subtracting the remainder from [prod1 prod0].
                  uint256 remainder;
                  assembly {
                      // Compute remainder using mulmod.
                      remainder := mulmod(x, y, denominator)
                      // Subtract 256 bit number from 512 bit number.
                      prod1 := sub(prod1, gt(remainder, prod0))
                      prod0 := sub(prod0, remainder)
                  }
                  // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                  // See https://cs.stackexchange.com/q/138556/92363.
                  // Does not overflow because the denominator cannot be zero at this stage in the function.
                  uint256 twos = denominator & (~denominator + 1);
                  assembly {
                      // Divide denominator by twos.
                      denominator := div(denominator, twos)
                      // Divide [prod1 prod0] by twos.
                      prod0 := div(prod0, twos)
                      // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                      twos := add(div(sub(0, twos), twos), 1)
                  }
                  // Shift in bits from prod1 into prod0.
                  prod0 |= prod1 * twos;
                  // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                  // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                  // four bits. That is, denominator * inv = 1 mod 2^4.
                  uint256 inverse = (3 * denominator) ^ 2;
                  // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                  // in modular arithmetic, doubling the correct bits in each step.
                  inverse *= 2 - denominator * inverse; // inverse mod 2^8
                  inverse *= 2 - denominator * inverse; // inverse mod 2^16
                  inverse *= 2 - denominator * inverse; // inverse mod 2^32
                  inverse *= 2 - denominator * inverse; // inverse mod 2^64
                  inverse *= 2 - denominator * inverse; // inverse mod 2^128
                  inverse *= 2 - denominator * inverse; // inverse mod 2^256
                  // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                  // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                  // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                  // is no longer required.
                  result = prod0 * inverse;
                  return result;
              }
          }
          /**
           * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
           */
          function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
              uint256 result = mulDiv(x, y, denominator);
              if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                  result += 1;
              }
              return result;
          }
          /**
           * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
           *
           * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
           */
          function sqrt(uint256 a) internal pure returns (uint256) {
              if (a == 0) {
                  return 0;
              }
              // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
              //
              // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
              // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
              //
              // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
              // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
              // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
              //
              // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
              uint256 result = 1 << (log2(a) >> 1);
              // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
              // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
              // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
              // into the expected uint128 result.
              unchecked {
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  return min(result, a / result);
              }
          }
          /**
           * @notice Calculates sqrt(a), following the selected rounding direction.
           */
          function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
              unchecked {
                  uint256 result = sqrt(a);
                  return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
              }
          }
          /**
           * @dev Return the log in base 2, rounded down, of a positive value.
           * Returns 0 if given 0.
           */
          function log2(uint256 value) internal pure returns (uint256) {
              uint256 result = 0;
              unchecked {
                  if (value >> 128 > 0) {
                      value >>= 128;
                      result += 128;
                  }
                  if (value >> 64 > 0) {
                      value >>= 64;
                      result += 64;
                  }
                  if (value >> 32 > 0) {
                      value >>= 32;
                      result += 32;
                  }
                  if (value >> 16 > 0) {
                      value >>= 16;
                      result += 16;
                  }
                  if (value >> 8 > 0) {
                      value >>= 8;
                      result += 8;
                  }
                  if (value >> 4 > 0) {
                      value >>= 4;
                      result += 4;
                  }
                  if (value >> 2 > 0) {
                      value >>= 2;
                      result += 2;
                  }
                  if (value >> 1 > 0) {
                      result += 1;
                  }
              }
              return result;
          }
          /**
           * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
           * Returns 0 if given 0.
           */
          function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
              unchecked {
                  uint256 result = log2(value);
                  return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
              }
          }
          /**
           * @dev Return the log in base 10, rounded down, of a positive value.
           * Returns 0 if given 0.
           */
          function log10(uint256 value) internal pure returns (uint256) {
              uint256 result = 0;
              unchecked {
                  if (value >= 10 ** 64) {
                      value /= 10 ** 64;
                      result += 64;
                  }
                  if (value >= 10 ** 32) {
                      value /= 10 ** 32;
                      result += 32;
                  }
                  if (value >= 10 ** 16) {
                      value /= 10 ** 16;
                      result += 16;
                  }
                  if (value >= 10 ** 8) {
                      value /= 10 ** 8;
                      result += 8;
                  }
                  if (value >= 10 ** 4) {
                      value /= 10 ** 4;
                      result += 4;
                  }
                  if (value >= 10 ** 2) {
                      value /= 10 ** 2;
                      result += 2;
                  }
                  if (value >= 10 ** 1) {
                      result += 1;
                  }
              }
              return result;
          }
          /**
           * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
           * Returns 0 if given 0.
           */
          function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
              unchecked {
                  uint256 result = log10(value);
                  return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
              }
          }
          /**
           * @dev Return the log in base 256, rounded down, of a positive value.
           * Returns 0 if given 0.
           *
           * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
           */
          function log256(uint256 value) internal pure returns (uint256) {
              uint256 result = 0;
              unchecked {
                  if (value >> 128 > 0) {
                      value >>= 128;
                      result += 16;
                  }
                  if (value >> 64 > 0) {
                      value >>= 64;
                      result += 8;
                  }
                  if (value >> 32 > 0) {
                      value >>= 32;
                      result += 4;
                  }
                  if (value >> 16 > 0) {
                      value >>= 16;
                      result += 2;
                  }
                  if (value >> 8 > 0) {
                      result += 1;
                  }
              }
              return result;
          }
          /**
           * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
           * Returns 0 if given 0.
           */
          function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
              unchecked {
                  uint256 result = log256(value);
                  return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Standard signed math utilities missing in the Solidity language.
       */
      library SignedMath {
          /**
           * @dev Returns the largest of two signed numbers.
           */
          function max(int256 a, int256 b) internal pure returns (int256) {
              return a > b ? a : b;
          }
          /**
           * @dev Returns the smallest of two signed numbers.
           */
          function min(int256 a, int256 b) internal pure returns (int256) {
              return a < b ? a : b;
          }
          /**
           * @dev Returns the average of two signed numbers without overflow.
           * The result is rounded towards zero.
           */
          function average(int256 a, int256 b) internal pure returns (int256) {
              // Formula from the book "Hacker's Delight"
              int256 x = (a & b) + ((a ^ b) >> 1);
              return x + (int256(uint256(x) >> 255) & (a ^ b));
          }
          /**
           * @dev Returns the absolute unsigned value of a signed value.
           */
          function abs(int256 n) internal pure returns (uint256) {
              unchecked {
                  // must be unchecked in order to support `n = type(int256).min`
                  return uint256(n >= 0 ? n : -n);
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
      // This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
      pragma solidity ^0.8.0;
      /**
       * @dev Library for reading and writing primitive types to specific storage slots.
       *
       * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
       * This library helps with reading and writing to such slots without the need for inline assembly.
       *
       * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
       *
       * Example usage to set ERC1967 implementation slot:
       * ```solidity
       * contract ERC1967 {
       *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
       *
       *     function _getImplementation() internal view returns (address) {
       *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
       *     }
       *
       *     function _setImplementation(address newImplementation) internal {
       *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
       *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
       *     }
       * }
       * ```
       *
       * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
       * _Available since v4.9 for `string`, `bytes`._
       */
      library StorageSlot {
          struct AddressSlot {
              address value;
          }
          struct BooleanSlot {
              bool value;
          }
          struct Bytes32Slot {
              bytes32 value;
          }
          struct Uint256Slot {
              uint256 value;
          }
          struct StringSlot {
              string value;
          }
          struct BytesSlot {
              bytes value;
          }
          /**
           * @dev Returns an `AddressSlot` with member `value` located at `slot`.
           */
          function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
              /// @solidity memory-safe-assembly
              assembly {
                  r.slot := slot
              }
          }
          /**
           * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
           */
          function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
              /// @solidity memory-safe-assembly
              assembly {
                  r.slot := slot
              }
          }
          /**
           * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
           */
          function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
              /// @solidity memory-safe-assembly
              assembly {
                  r.slot := slot
              }
          }
          /**
           * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
           */
          function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
              /// @solidity memory-safe-assembly
              assembly {
                  r.slot := slot
              }
          }
          /**
           * @dev Returns an `StringSlot` with member `value` located at `slot`.
           */
          function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
              /// @solidity memory-safe-assembly
              assembly {
                  r.slot := slot
              }
          }
          /**
           * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
           */
          function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
              /// @solidity memory-safe-assembly
              assembly {
                  r.slot := store.slot
              }
          }
          /**
           * @dev Returns an `BytesSlot` with member `value` located at `slot`.
           */
          function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
              /// @solidity memory-safe-assembly
              assembly {
                  r.slot := slot
              }
          }
          /**
           * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
           */
          function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
              /// @solidity memory-safe-assembly
              assembly {
                  r.slot := store.slot
              }
          }
      }