ETH Price: $2,403.41 (+7.50%)

Transaction Decoder

Block:
15732585 at Oct-12-2022 02:20:11 PM +UTC
Transaction Fee:
0.003859047281284226 ETH $9.27
Gas Used:
130,126 Gas / 29.656235351 Gwei

Emitted Events:

219 UniswapV2Pair.Transfer( from=[Receiver] YAMIncentivizer, to=[Sender] 0x70b8753dfc2095d6df00806cd820c5c73ccb44f7, value=1012750427027622630015 )
220 YAMIncentivizer.Withdrawn( user=[Sender] 0x70b8753dfc2095d6df00806cd820c5c73ccb44f7, amount=1012750427027622630015 )
221 YAMDelegator.Transfer( from=[Receiver] YAMIncentivizer, to=[Sender] 0x70b8753dfc2095d6df00806cd820c5c73ccb44f7, amount=440718490592259895882 )
222 YAMIncentivizer.RewardPaid( user=[Sender] 0x70b8753dfc2095d6df00806cd820c5c73ccb44f7, reward=440718490592259895882 )

Account State Difference:

  Address   Before After State Difference Code
0x0AaCfbeC...17C0d8521
0x5b0501F7...74b32a0Ed
(Yam.Finance: Incentivizer)
0x70B8753D...73CcB44f7
1.185952688581044077 Eth
Nonce: 485
1.182093641299759851 Eth
Nonce: 486
0.003859047281284226
(Eden Network: Builder)
3.354693224917179491 Eth3.354866370056829901 Eth0.00017314513965041
0xb93Cc053...5C031caBC

Execution Trace

YAMIncentivizer.CALL( )
  • UniswapV2Pair.transfer( to=0x70B8753DFC2095d6Df00806cD820c5c73CcB44f7, value=1012750427027622630015 ) => ( True )
  • YAMDelegator.CALL( )
  • YAMDelegator.transfer( dst=0x70B8753DFC2095d6Df00806cD820c5c73CcB44f7, amount=440718490592259895882 ) => ( True )
    • YAMDelegate3.transfer( to=0x70B8753DFC2095d6Df00806cD820c5c73CcB44f7, value=440718490592259895882 ) => ( True )
      File 1 of 4: YAMIncentivizer
      /*
         ____            __   __        __   _
        / __/__ __ ___  / /_ / /  ___  / /_ (_)__ __
       _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
      /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
           /___/
      
      * Synthetix: YAMIncentives.sol
      *
      * Docs: https://docs.synthetix.io/
      *
      *
      * MIT License
      * ===========
      *
      * Copyright (c) 2020 Synthetix
      *
      * Permission is hereby granted, free of charge, to any person obtaining a copy
      * of this software and associated documentation files (the "Software"), to deal
      * in the Software without restriction, including without limitation the rights
      * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      * copies of the Software, and to permit persons to whom the Software is
      * furnished to do so, subject to the following conditions:
      *
      * The above copyright notice and this permission notice shall be included in all
      * copies or substantial portions of the Software.
      *
      * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      */
      
      // File: @openzeppelin/contracts/math/Math.sol
      
      pragma solidity 0.5.15;
      
      /**
       * @dev Standard math utilities missing in the Solidity language.
       */
      library Math {
          /**
           * @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, so we distribute
              return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
          }
      }
      
      // File: @openzeppelin/contracts/math/SafeMath.sol
      
      pragma solidity 0.5.15;
      
      /**
       * @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.
           *
           * _Available since v2.4.0._
           */
          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.
           *
           * _Available since v2.4.0._
           */
          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.
           *
           * _Available since v2.4.0._
           */
          function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
              require(b != 0, errorMessage);
              return a % b;
          }
      }
      
      // File: @openzeppelin/contracts/GSN/Context.sol
      
      pragma solidity 0.5.15;
      
      /*
       * @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.
       */
      contract Context {
          // Empty internal constructor, to prevent people from mistakenly deploying
          // an instance of this contract, which should be used via inheritance.
          constructor () internal { }
          // solhint-disable-previous-line no-empty-blocks
      
          function _msgSender() internal view returns (address payable) {
              return msg.sender;
          }
      
          function _msgData() internal view returns (bytes memory) {
              this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
              return msg.data;
          }
      }
      
      // File: @openzeppelin/contracts/ownership/Ownable.sol
      
      pragma solidity 0.5.15;
      
      /**
       * @dev Contract module which provides a basic access control mechanism, where
       * there is an account (an owner) that can be granted exclusive access to
       * specific functions.
       *
       * This module is used through inheritance. It will make available the modifier
       * `onlyOwner`, which can be applied to your functions to restrict their use to
       * the owner.
       */
      contract Ownable is Context {
          address private _owner;
      
          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
      
          /**
           * @dev Initializes the contract setting the deployer as the initial owner.
           */
          constructor () internal {
              _owner = _msgSender();
              emit OwnershipTransferred(address(0), _owner);
          }
      
          /**
           * @dev Returns the address of the current owner.
           */
          function owner() public view returns (address) {
              return _owner;
          }
      
          /**
           * @dev Throws if called by any account other than the owner.
           */
          modifier onlyOwner() {
              require(isOwner(), "Ownable: caller is not the owner");
              _;
          }
      
          /**
           * @dev Returns true if the caller is the current owner.
           */
          function isOwner() public view returns (bool) {
              return _msgSender() == _owner;
          }
      
          /**
           * @dev Leaves the contract without owner. It will not be possible to call
           * `onlyOwner` functions anymore. Can only be called by the current owner.
           *
           * NOTE: Renouncing ownership will leave the contract without an owner,
           * thereby removing any functionality that is only available to the owner.
           */
          function renounceOwnership() public onlyOwner {
              emit OwnershipTransferred(_owner, address(0));
              _owner = address(0);
          }
      
          /**
           * @dev Transfers ownership of the contract to a new account (`newOwner`).
           * Can only be called by the current owner.
           */
          function transferOwnership(address newOwner) public onlyOwner {
              _transferOwnership(newOwner);
          }
      
          /**
           * @dev Transfers ownership of the contract to a new account (`newOwner`).
           */
          function _transferOwnership(address newOwner) internal {
              require(newOwner != address(0), "Ownable: new owner is the zero address");
              emit OwnershipTransferred(_owner, newOwner);
              _owner = newOwner;
          }
      }
      
      // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
      
      pragma solidity 0.5.15;
      
      /**
       * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
       * the optional functions; to access them see {ERC20Detailed}.
       */
      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);
          function mint(address account, uint amount) external;
      
          /**
           * @dev Returns the remaining number of tokens that `spender` will be
           * allowed to spend on behalf of `owner` through {transferFrom}. This is
           * zero by default.
           *
           * This value changes when {approve} or {transferFrom} are called.
           */
          function allowance(address owner, address spender) external view returns (uint256);
      
          /**
           * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * IMPORTANT: Beware that changing an allowance with this method brings the risk
           * that someone may use both the old and the new allowance by unfortunate
           * transaction ordering. One possible solution to mitigate this race
           * condition is to first reduce the spender's allowance to 0 and set the
           * desired value afterwards:
           * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
           *
           * Emits an {Approval} event.
           */
          function approve(address spender, uint256 amount) external returns (bool);
      
          /**
           * @dev Moves `amount` tokens from `sender` to `recipient` using the
           * allowance mechanism. `amount` is then deducted from the caller's
           * allowance.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * Emits a {Transfer} event.
           */
          function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
      
          /**
           * @dev Emitted when `value` tokens are moved from one account (`from`) to
           * another (`to`).
           *
           * Note that `value` may be zero.
           */
          event Transfer(address indexed from, address indexed to, uint256 value);
      
          /**
           * @dev Emitted when the allowance of a `spender` for an `owner` is set by
           * a call to {approve}. `value` is the new allowance.
           */
          event Approval(address indexed owner, address indexed spender, uint256 value);
      }
      
      // File: @openzeppelin/contracts/utils/Address.sol
      
      pragma solidity 0.5.15;
      
      /**
       * @dev Collection of functions related to the address type
       */
      library Address {
          /**
           * @dev Returns true if `account` is a contract.
           *
           * This test is non-exhaustive, and there may be false-negatives: during the
           * execution of a contract's constructor, its address will be reported as
           * not containing 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.
           */
          function isContract(address account) internal view returns (bool) {
              // This method relies in extcodesize, which returns 0 for contracts in
              // construction, since the code is only stored at the end of the
              // constructor execution.
      
              // 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 != 0x0 && codehash != accountHash);
          }
      
          /**
           * @dev Converts an `address` into `address payable`. Note that this is
           * simply a type cast: the actual underlying value is not changed.
           *
           * _Available since v2.4.0._
           */
          function toPayable(address account) internal pure returns (address payable) {
              return address(uint160(account));
          }
      
          /**
           * @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].
           *
           * _Available since v2.4.0._
           */
          function sendValue(address payable recipient, uint256 amount) internal {
              require(address(this).balance >= amount, "Address: insufficient balance");
      
              // solhint-disable-next-line avoid-call-value
              (bool success, ) = recipient.call.value(amount)("");
              require(success, "Address: unable to send value, recipient may have reverted");
          }
      }
      
      // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
      
      pragma solidity 0.5.15;
      
      
      
      
      /**
       * @title SafeERC20
       * @dev Wrappers around ERC20 operations that throw on failure (when the token
       * contract returns false). Tokens that return no value (and instead revert or
       * throw on failure) are also supported, non-reverting calls are assumed to be
       * successful.
       * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
       * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
       */
      library SafeERC20 {
          using SafeMath for uint256;
          using Address for address;
      
          function safeTransfer(IERC20 token, address to, uint256 value) internal {
              callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
          }
      
          function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
              callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
          }
      
          function safeApprove(IERC20 token, address spender, uint256 value) internal {
              // safeApprove should only be called when setting an initial allowance,
              // or when resetting it to zero. To increase and decrease it, use
              // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
              // solhint-disable-next-line max-line-length
              require((value == 0) || (token.allowance(address(this), spender) == 0),
                  "SafeERC20: approve from non-zero to non-zero allowance"
              );
              callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
          }
      
          function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
              uint256 newAllowance = token.allowance(address(this), spender).add(value);
              callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
          }
      
          function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
              uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
              callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
          }
      
          /**
           * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
           * on the return value: the return value is optional (but if data is returned, it must not be false).
           * @param token The token targeted by the call.
           * @param data The call data (encoded using abi.encode or one of its variants).
           */
          function callOptionalReturn(IERC20 token, bytes memory data) private {
              // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
              // we're implementing it ourselves.
      
              // A Solidity high level call has three parts:
              //  1. The target address is checked to verify it contains contract code
              //  2. The call itself is made, and success asserted
              //  3. The return value is decoded, which in turn checks the size of the returned data.
              // solhint-disable-next-line max-line-length
              require(address(token).isContract(), "SafeERC20: call to non-contract");
      
              // solhint-disable-next-line avoid-low-level-calls
              (bool success, bytes memory returndata) = address(token).call(data);
              require(success, "SafeERC20: low-level call failed");
      
              if (returndata.length > 0) { // Return data is optional
                  // solhint-disable-next-line max-line-length
                  require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
              }
          }
      }
      
      // File: contracts/IRewardDistributionRecipient.sol
      
      pragma solidity 0.5.15;
      
      
      
      contract IRewardDistributionRecipient is Ownable {
          address public rewardDistribution;
      
          function notifyRewardAmount(uint256 reward) external;
      
          modifier onlyRewardDistribution() {
              require(_msgSender() == rewardDistribution, "Caller is not reward distribution");
              _;
          }
      
          function setRewardDistribution(address _rewardDistribution)
              external
              onlyOwner
          {
              rewardDistribution = _rewardDistribution;
          }
      }
      
      // File: contracts/CurveRewards.sol
      
      pragma solidity 0.5.15;
      
      
      
      
      
      
      contract LPTokenWrapper {
          using SafeMath for uint256;
          using SafeERC20 for IERC20;
      
          IERC20 public uni_lp = IERC20(0xb93Cc05334093c6B3b8Bfd29933bb8d5C031caBC);
      
          uint256 private _totalSupply;
      
          mapping(address => uint256) private _balances;
      
          function totalSupply() public view returns (uint256) {
              return _totalSupply;
          }
      
          function balanceOf(address account) public view returns (uint256) {
              return _balances[account];
          }
      
          function stake(uint256 amount) public {
              _totalSupply = _totalSupply.add(amount);
              _balances[msg.sender] = _balances[msg.sender].add(amount);
              uni_lp.safeTransferFrom(msg.sender, address(this), amount);
          }
      
          function withdraw(uint256 amount) public {
              _totalSupply = _totalSupply.sub(amount);
              _balances[msg.sender] = _balances[msg.sender].sub(amount);
              uni_lp.safeTransfer(msg.sender, amount);
          }
      }
      
      interface YAM {
          function yamsScalingFactor() external returns (uint256);
          function mint(address to, uint256 amount) external;
      }
      
      contract YAMIncentivizer is LPTokenWrapper, IRewardDistributionRecipient {
          IERC20 public yam = IERC20(0x0AaCfbeC6a24756c20D41914F2caba817C0d8521);
          uint256 public constant DURATION = 7 days;
      
          uint256 public initreward = 925 * 10**2 * 10**18; // 92.5k
          uint256 public starttime = 1600545600; // 2020-09-19 8:00:00 PM (UTC +00:00)
          uint256 public periodFinish = 0;
          uint256 public rewardRate = 0;
          uint256 public lastUpdateTime;
          uint256 public rewardPerTokenStored;
      
          bool public initialized = false;
          bool public breaker;
      
          mapping(address => uint256) public userRewardPerTokenPaid;
          mapping(address => uint256) public rewards;
      
      
          event RewardAdded(uint256 reward);
          event Staked(address indexed user, uint256 amount);
          event Withdrawn(address indexed user, uint256 amount);
          event RewardPaid(address indexed user, uint256 reward);
      
          modifier updateReward(address account) {
              rewardPerTokenStored = rewardPerToken();
              lastUpdateTime = lastTimeRewardApplicable();
              if (account != address(0)) {
                  rewards[account] = earned(account);
                  userRewardPerTokenPaid[account] = rewardPerTokenStored;
              }
              _;
          }
      
          function lastTimeRewardApplicable() public view returns (uint256) {
              return Math.min(block.timestamp, periodFinish);
          }
      
          function rewardPerToken() public view returns (uint256) {
              if (totalSupply() == 0) {
                  return rewardPerTokenStored;
              }
              return
                  rewardPerTokenStored.add(
                      lastTimeRewardApplicable()
                          .sub(lastUpdateTime)
                          .mul(rewardRate)
                          .mul(1e18)
                          .div(totalSupply())
                  );
          }
      
          function earned(address account) public view returns (uint256) {
              return
                  balanceOf(account)
                      .mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
                      .div(1e18)
                      .add(rewards[account]);
          }
      
          // stake visibility is public as overriding LPTokenWrapper's stake() function
          function stake(uint256 amount) public updateReward(msg.sender) checkhalve checkStart {
              require(amount > 0, "Cannot stake 0");
              super.stake(amount);
              emit Staked(msg.sender, amount);
          }
      
          function withdraw(uint256 amount) public updateReward(msg.sender) checkStart {
              require(amount > 0, "Cannot withdraw 0");
              super.withdraw(amount);
              emit Withdrawn(msg.sender, amount);
          }
      
          function exit() external {
              withdraw(balanceOf(msg.sender));
              getReward();
          }
      
          function getReward() public updateReward(msg.sender) checkhalve checkStart {
              uint256 reward = earned(msg.sender);
              if (reward > 0) {
                  rewards[msg.sender] = 0;
                  uint256 scalingFactor = YAM(address(yam)).yamsScalingFactor();
                  uint256 trueReward = reward.mul(scalingFactor).div(10**18);
                  yam.safeTransfer(msg.sender, trueReward);
                  emit RewardPaid(msg.sender, trueReward);
              }
          }
      
          modifier checkhalve() {
              if (breaker) {
                // do nothing
              } else if (block.timestamp >= periodFinish) {
                  initreward = initreward.mul(90).div(100);
                  uint256 scalingFactor = YAM(address(yam)).yamsScalingFactor();
                  uint256 newRewards = initreward.mul(scalingFactor).div(10**18);
                  yam.mint(address(this), newRewards);
      
                  rewardRate = initreward.div(DURATION);
                  periodFinish = block.timestamp.add(DURATION);
                  emit RewardAdded(initreward);
              }
              _;
          }
      
          modifier checkStart(){
              require(block.timestamp >= starttime,"not start");
              _;
          }
      
      
          function notifyRewardAmount(uint256 reward)
              external
              onlyRewardDistribution
              updateReward(address(0))
          {
              // https://sips.synthetix.io/sips/sip-77
              require(reward < uint256(-1) / 10**18, "rewards too large, would lock");
              if (block.timestamp > starttime) {
                if (block.timestamp >= periodFinish) {
                    rewardRate = reward.div(DURATION);
                } else {
                    uint256 remaining = periodFinish.sub(block.timestamp);
                    uint256 leftover = remaining.mul(rewardRate);
                    rewardRate = reward.add(leftover).div(DURATION);
                }
                lastUpdateTime = block.timestamp;
                periodFinish = block.timestamp.add(DURATION);
                emit RewardAdded(reward);
              } else {
                require(initreward < uint256(-1) / 10**18, "rewards too large, would lock");
                require(!initialized, "already initialized");
                initialized = true;
                yam.mint(address(this), initreward);
                rewardRate = initreward.div(DURATION);
                lastUpdateTime = starttime;
                periodFinish = starttime.add(DURATION);
                emit RewardAdded(reward);
              }
          }
      
      
          // This function allows governance to take unsupported tokens out of the
          // contract, since this one exists longer than the other pools.
          // This is in an effort to make someone whole, should they seriously
          // mess up. There is no guarantee governance will vote to return these.
          // It also allows for removal of airdropped tokens.
          function rescueTokens(IERC20 _token, uint256 amount, address to)
              external
          {
              // only gov
              require(msg.sender == owner(), "!governance");
              // cant take staked asset
              require(_token != uni_lp, "uni_lp");
              // cant take reward asset
              require(_token != yam, "yam");
      
              // transfer to
              _token.safeTransfer(to, amount);
          }
      
          function setBreaker(bool breaker_)
              external
          {
              // only gov
              require(msg.sender == owner(), "!governance");
              breaker = breaker_;
          }
      }

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

      File 3 of 4: YAMDelegator
      pragma solidity 0.5.15;
      
      
      // YAM v3 Token Proxy
      
      /**
       * @dev Wrappers over Solidity's arithmetic operations with added overflow
       * checks.
       *
       * Arithmetic operations in Solidity wrap on overflow. This can easily result
       * in bugs, because programmers usually assume that an overflow raises an
       * error, which is the standard behavior in high level programming languages.
       * `SafeMath` restores this intuition by reverting the transaction when an
       * operation overflows.
       *
       * Using this library instead of the unchecked operations eliminates an entire
       * class of bugs, so it's recommended to use it always.
       */
      library SafeMath {
          /**
           * @dev Returns the addition of two unsigned integers, reverting on
           * overflow.
           *
           * Counterpart to Solidity's `+` operator.
           *
           * Requirements:
           *
           * - Addition cannot overflow.
           */
          function add(uint256 a, uint256 b) internal pure returns (uint256) {
              uint256 c = a + b;
              require(c >= a, "SafeMath: addition overflow");
      
              return c;
          }
      
          /**
           * @dev Returns the subtraction of two unsigned integers, reverting on
           * overflow (when the result is negative).
           *
           * Counterpart to Solidity's `-` operator.
           *
           * Requirements:
           *
           * - Subtraction cannot overflow.
           */
          function sub(uint256 a, uint256 b) internal pure returns (uint256) {
              return sub(a, b, "SafeMath: subtraction overflow");
          }
      
          /**
           * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
           * overflow (when the result is negative).
           *
           * Counterpart to Solidity's `-` operator.
           *
           * Requirements:
           *
           * - Subtraction cannot overflow.
           */
          function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
              require(b <= a, errorMessage);
              uint256 c = a - b;
      
              return c;
          }
      
          /**
           * @dev Returns the multiplication of two unsigned integers, reverting on
           * overflow.
           *
           * Counterpart to Solidity's `*` operator.
           *
           * Requirements:
           *
           * - Multiplication cannot overflow.
           */
          function mul(uint256 a, uint256 b) internal pure returns (uint256) {
              // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
              // benefit is lost if 'b' is also tested.
              // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
              if (a == 0) {
                  return 0;
              }
      
              uint256 c = a * b;
              require(c / a == b, "SafeMath: multiplication overflow");
      
              return c;
          }
      
          /**
           * @dev Returns the integer division of two unsigned integers. Reverts on
           * division by zero. The result is rounded towards zero.
           *
           * Counterpart to Solidity's `/` operator. Note: this function uses a
           * `revert` opcode (which leaves remaining gas untouched) while Solidity
           * uses an invalid opcode to revert (consuming all remaining gas).
           *
           * Requirements:
           *
           * - The divisor cannot be zero.
           */
          function div(uint256 a, uint256 b) internal pure returns (uint256) {
              return div(a, b, "SafeMath: division by zero");
          }
      
          /**
           * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
           * division by zero. The result is rounded towards zero.
           *
           * Counterpart to Solidity's `/` operator. Note: this function uses a
           * `revert` opcode (which leaves remaining gas untouched) while Solidity
           * uses an invalid opcode to revert (consuming all remaining gas).
           *
           * Requirements:
           *
           * - The divisor cannot be zero.
           */
          function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
              require(b > 0, errorMessage);
              uint256 c = a / b;
              // assert(a == b * c + a % b); // There is no case in which this doesn't hold
      
              return c;
          }
      
          /**
           * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
           * Reverts when dividing by zero.
           *
           * Counterpart to Solidity's `%` operator. This function uses a `revert`
           * opcode (which leaves remaining gas untouched) while Solidity uses an
           * invalid opcode to revert (consuming all remaining gas).
           *
           * Requirements:
           *
           * - The divisor cannot be zero.
           */
          function mod(uint256 a, uint256 b) internal pure returns (uint256) {
              return mod(a, b, "SafeMath: modulo by zero");
          }
      
          /**
           * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
           * Reverts with custom message when dividing by zero.
           *
           * Counterpart to Solidity's `%` operator. This function uses a `revert`
           * opcode (which leaves remaining gas untouched) while Solidity uses an
           * invalid opcode to revert (consuming all remaining gas).
           *
           * Requirements:
           *
           * - The divisor cannot be zero.
           */
          function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
              require(b != 0, errorMessage);
              return a % b;
          }
      }
      
      
      // Storage for a YAM token
      contract YAMTokenStorage {
      
          using SafeMath for uint256;
      
          /**
           * @dev Guard variable for re-entrancy checks. Not currently used
           */
          bool internal _notEntered;
      
          /**
           * @notice EIP-20 token name for this token
           */
          string public name;
      
          /**
           * @notice EIP-20 token symbol for this token
           */
          string public symbol;
      
          /**
           * @notice EIP-20 token decimals for this token
           */
          uint8 public decimals;
      
          /**
           * @notice Governor for this contract
           */
          address public gov;
      
          /**
           * @notice Pending governance for this contract
           */
          address public pendingGov;
      
          /**
           * @notice Approved rebaser for this contract
           */
          address public rebaser;
      
          /**
           * @notice Approved migrator for this contract
           */
          address public migrator;
      
          /**
           * @notice Incentivizer address of YAM protocol
           */
          address public incentivizer;
      
          /**
           * @notice Total supply of YAMs
           */
          uint256 public totalSupply;
      
          /**
           * @notice Internal decimals used to handle scaling factor
           */
          uint256 public constant internalDecimals = 10**24;
      
          /**
           * @notice Used for percentage maths
           */
          uint256 public constant BASE = 10**18;
      
          /**
           * @notice Scaling factor that adjusts everyone's balances
           */
          uint256 public yamsScalingFactor;
      
          mapping (address => uint256) internal _yamBalances;
      
          mapping (address => mapping (address => uint256)) internal _allowedFragments;
      
          uint256 public initSupply;
      
      
          // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
          bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
          bytes32 public DOMAIN_SEPARATOR;
      }
      
      /* Copyright 2020 Compound Labs, Inc.
      
      Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
      
      1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
      
      2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
      
      3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
      
      THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
      
      
      contract YAMGovernanceStorage {
          /// @notice A record of each accounts delegate
          mapping (address => address) internal _delegates;
      
          /// @notice A checkpoint for marking number of votes from a given block
          struct Checkpoint {
              uint32 fromBlock;
              uint256 votes;
          }
      
          /// @notice A record of votes checkpoints for each account, by index
          mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
      
          /// @notice The number of checkpoints for each account
          mapping (address => uint32) public numCheckpoints;
      
          /// @notice The EIP-712 typehash for the contract's domain
          bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
      
          /// @notice The EIP-712 typehash for the delegation struct used by the contract
          bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
      
          /// @notice A record of states for signing / validating signatures
          mapping (address => uint) public nonces;
      }
      
      
      contract YAMTokenInterface is YAMTokenStorage, YAMGovernanceStorage {
      
          /// @notice An event thats emitted when an account changes its delegate
          event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
      
          /// @notice An event thats emitted when a delegate account's vote balance changes
          event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
      
          /**
           * @notice Event emitted when tokens are rebased
           */
          event Rebase(uint256 epoch, uint256 prevYamsScalingFactor, uint256 newYamsScalingFactor);
      
          /*** Gov Events ***/
      
          /**
           * @notice Event emitted when pendingGov is changed
           */
          event NewPendingGov(address oldPendingGov, address newPendingGov);
      
          /**
           * @notice Event emitted when gov is changed
           */
          event NewGov(address oldGov, address newGov);
      
          /**
           * @notice Sets the rebaser contract
           */
          event NewRebaser(address oldRebaser, address newRebaser);
      
          /**
           * @notice Sets the migrator contract
           */
          event NewMigrator(address oldMigrator, address newMigrator);
      
          /**
           * @notice Sets the incentivizer contract
           */
          event NewIncentivizer(address oldIncentivizer, address newIncentivizer);
      
          /* - ERC20 Events - */
      
          /**
           * @notice EIP20 Transfer event
           */
          event Transfer(address indexed from, address indexed to, uint amount);
      
          /**
           * @notice EIP20 Approval event
           */
          event Approval(address indexed owner, address indexed spender, uint amount);
      
          /* - Extra Events - */
          /**
           * @notice Tokens minted event
           */
          event Mint(address to, uint256 amount);
      
          // Public functions
          function transfer(address to, uint256 value) external returns(bool);
          function transferFrom(address from, address to, uint256 value) external returns(bool);
          function balanceOf(address who) external view returns(uint256);
          function balanceOfUnderlying(address who) external view returns(uint256);
          function allowance(address owner_, address spender) external view returns(uint256);
          function approve(address spender, uint256 value) external returns (bool);
          function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
          function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
          function maxScalingFactor() external view returns (uint256);
          function yamToFragment(uint256 yam) external view returns (uint256);
          function fragmentToYam(uint256 value) external view returns (uint256);
      
          /* - Governance Functions - */
          function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
          function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
          function delegate(address delegatee) external;
          function delegates(address delegator) external view returns (address);
          function getCurrentVotes(address account) external view returns (uint256);
      
          /* - Permissioned/Governance functions - */
          function mint(address to, uint256 amount) external returns (bool);
          function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256);
          function _setRebaser(address rebaser_) external;
          function _setIncentivizer(address incentivizer_) external;
          function _setPendingGov(address pendingGov_) external;
          function _acceptGov() external;
      }
      
      contract YAMDelegationStorage {
          /**
           * @notice Implementation address for this contract
           */
          address public implementation;
      }
      
      contract YAMDelegatorInterface is YAMDelegationStorage {
          /**
           * @notice Emitted when implementation is changed
           */
          event NewImplementation(address oldImplementation, address newImplementation);
      
          /**
           * @notice Called by the gov to update the implementation of the delegator
           * @param implementation_ The address of the new implementation for delegation
           * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
           * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
           */
          function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
      }
      
      
      contract YAMDelegator is YAMTokenInterface, YAMDelegatorInterface {
          /**
           * @notice Construct a new YAM
           * @param name_ ERC-20 name of this token
           * @param symbol_ ERC-20 symbol of this token
           * @param decimals_ ERC-20 decimal precision of this token
           * @param initTotalSupply_ Initial token amount
           * @param implementation_ The address of the implementation the contract delegates to
           * @param becomeImplementationData The encoded args for becomeImplementation
           */
          constructor(
              string memory name_,
              string memory symbol_,
              uint8 decimals_,
              uint256 initTotalSupply_,
              address implementation_,
              bytes memory becomeImplementationData
          )
              public
          {
      
      
              // Creator of the contract is gov during initialization
              gov = msg.sender;
      
              // First delegate gets to initialize the delegator (i.e. storage contract)
              delegateTo(
                  implementation_,
                  abi.encodeWithSignature(
                      "initialize(string,string,uint8,address,uint256)",
                      name_,
                      symbol_,
                      decimals_,
                      msg.sender,
                      initTotalSupply_
                  )
              );
      
              // New implementations always get set via the settor (post-initialize)
              _setImplementation(implementation_, false, becomeImplementationData);
      
          }
      
          /**
           * @notice Called by the gov to update the implementation of the delegator
           * @param implementation_ The address of the new implementation for delegation
           * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
           * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
           */
          function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
              require(msg.sender == gov, "YAMDelegator::_setImplementation: Caller must be gov");
      
              if (allowResign) {
                  delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
              }
      
              address oldImplementation = implementation;
              implementation = implementation_;
      
              delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
      
              emit NewImplementation(oldImplementation, implementation);
          }
      
          /**
           * @notice Sender supplies assets into the market and receives cTokens in exchange
           * @dev Accrues interest whether or not the operation succeeds, unless reverted
           * @param mintAmount The amount of the underlying asset to supply
           * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
           */
          function mint(address to, uint256 mintAmount)
              external
              returns (bool)
          {
              to; mintAmount; // Shh
              delegateAndReturn();
          }
      
          /**
           * @notice Transfer `amount` tokens from `msg.sender` to `dst`
           * @param dst The address of the destination account
           * @param amount The number of tokens to transfer
           * @return Whether or not the transfer succeeded
           */
          function transfer(address dst, uint256 amount)
              external
              returns (bool)
          {
              dst; amount; // Shh
              delegateAndReturn();
          }
      
          /**
           * @notice Transfer `amount` tokens from `src` to `dst`
           * @param src The address of the source account
           * @param dst The address of the destination account
           * @param amount The number of tokens to transfer
           * @return Whether or not the transfer succeeded
           */
          function transferFrom(
              address src,
              address dst,
              uint256 amount
          )
              external
              returns (bool)
          {
              src; dst; amount; // Shh
              delegateAndReturn();
          }
      
          /**
           * @notice Approve `spender` to transfer up to `amount` from `src`
           * @dev This will overwrite the approval amount for `spender`
           *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
           * @param spender The address of the account which may transfer tokens
           * @param amount The number of tokens that are approved (-1 means infinite)
           * @return Whether or not the approval succeeded
           */
          function approve(
              address spender,
              uint256 amount
          )
              external
              returns (bool)
          {
              spender; amount; // Shh
              delegateAndReturn();
          }
      
          /**
           * @dev Increase the amount of tokens that an owner has allowed to a spender.
           * This method should be used instead of approve() to avoid the double approval vulnerability
           * described above.
           * @param spender The address which will spend the funds.
           * @param addedValue The amount of tokens to increase the allowance by.
           */
          function increaseAllowance(
              address spender,
              uint256 addedValue
          )
              external
              returns (bool)
          {
              spender; addedValue; // Shh
              delegateAndReturn();
          }
      
      
      
          function maxScalingFactor()
              external
              view
              returns (uint256)
          {
              delegateToViewAndReturn();
          }
      
          function rebase(
              uint256 epoch,
              uint256 indexDelta,
              bool positive
          )
              external
              returns (uint256)
          {
              epoch; indexDelta; positive;
              delegateAndReturn();
          }
      
          /**
           * @dev Decrease the amount of tokens that an owner has allowed to a spender.
           *
           * @param spender The address which will spend the funds.
           * @param subtractedValue The amount of tokens to decrease the allowance by.
           */
          function decreaseAllowance(
              address spender,
              uint256 subtractedValue
          )
              external
              returns (bool)
          {
              spender; subtractedValue; // Shh
              delegateAndReturn();
          }
      
      
          // --- Approve by signature ---
          function permit(
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          )
              external
          {
              owner; spender; value; deadline; v; r; s; // Shh
              delegateAndReturn();
          }
      
          /**
           * @notice Get the current allowance from `owner` for `spender`
           * @param owner The address of the account which owns the tokens to be spent
           * @param spender The address of the account which may transfer tokens
           * @return The number of tokens allowed to be spent (-1 means infinite)
           */
          function allowance(
              address owner,
              address spender
          )
              external
              view
              returns (uint256)
          {
              owner; spender; // Shh
              delegateToViewAndReturn();
          }
      
      
          /**
           * @notice Rescues tokens and sends them to the `to` address
           * @param token The address of the token
           * @param to The address for which the tokens should be send
           * @return Success
           */
          function rescueTokens(
              address token,
              address to,
              uint256 amount
          )
              external
              returns (bool)
          {
              token; to; amount; // Shh
              delegateAndReturn();
          }
      
          /**
           * @notice Get the current allowance from `owner` for `spender`
           * @param delegator The address of the account which has designated a delegate
           * @return Address of delegatee
           */
          function delegates(
              address delegator
          )
              external
              view
              returns (address)
          {
              delegator; // Shh
              delegateToViewAndReturn();
          }
      
          /**
           * @notice Get the token balance of the `owner`
           * @param owner The address of the account to query
           * @return The number of tokens owned by `owner`
           */
          function balanceOf(address owner)
              external
              view
              returns (uint256)
          {
              owner; // Shh
              delegateToViewAndReturn();
          }
      
          /**
           * @notice Currently unused. For future compatability
           * @param owner The address of the account to query
           * @return The number of underlying tokens owned by `owner`
           */
          function balanceOfUnderlying(address owner)
              external
              view
              returns (uint256)
          {
              owner; // Shh
              delegateToViewAndReturn();
          }
      
          /*** Gov Functions ***/
      
          /**
            * @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
            * @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
            * @param newPendingGov New pending gov.
            */
          function _setPendingGov(address newPendingGov)
              external
          {
              newPendingGov; // Shh
              delegateAndReturn();
          }
      
          function _setRebaser(address rebaser_)
              external
          {
              rebaser_; // Shh
              delegateAndReturn();
          }
      
          function _setIncentivizer(address incentivizer_)
              external
          {
              incentivizer_; // Shh
              delegateAndReturn();
          }
      
          function _setMigrator(address migrator_)
              external
          {
              migrator_; // Shh
              delegateAndReturn();
          }
      
          /**
            * @notice Accepts transfer of gov rights. msg.sender must be pendingGov
            * @dev Gov function for pending gov to accept role and update gov
            * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
            */
          function _acceptGov()
              external
          {
              delegateAndReturn();
          }
      
      
          function getPriorVotes(address account, uint blockNumber)
              external
              view
              returns (uint256)
          {
              account; blockNumber;
              delegateToViewAndReturn();
          }
      
          function delegateBySig(
              address delegatee,
              uint nonce,
              uint expiry,
              uint8 v,
              bytes32 r,
              bytes32 s
          )
              external
          {
              delegatee; nonce; expiry; v; r; s;
              delegateAndReturn();
          }
      
          function delegate(address delegatee)
              external
          {
              delegatee;
              delegateAndReturn();
          }
      
          function getCurrentVotes(address account)
              external
              view
              returns (uint256)
          {
              account;
              delegateToViewAndReturn();
          }
      
      
          function yamToFragment(uint256 yam)
              external
              view
              returns (uint256)
          {
              yam;
              delegateToViewAndReturn();
          }
      
          function fragmentToYam(uint256 value)
              external
              view
              returns (uint256)
          {
              value;
              delegateToViewAndReturn();
          }
      
          /**
           * @notice Internal method to delegate execution to another contract
           * @dev It returns to the external caller whatever the implementation returns or forwards reverts
           * @param callee The contract to delegatecall
           * @param data The raw data to delegatecall
           * @return The returned bytes from the delegatecall
           */
          function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
              (bool success, bytes memory returnData) = callee.delegatecall(data);
              assembly {
                  if eq(success, 0) {
                      revert(add(returnData, 0x20), returndatasize)
                  }
              }
              return returnData;
          }
      
          /**
           * @notice Delegates execution to the implementation contract
           * @dev It returns to the external caller whatever the implementation returns or forwards reverts
           * @param data The raw data to delegatecall
           * @return The returned bytes from the delegatecall
           */
          function delegateToImplementation(bytes memory data) public returns (bytes memory) {
              return delegateTo(implementation, data);
          }
      
          /**
           * @notice Delegates execution to an implementation contract
           * @dev It returns to the external caller whatever the implementation returns or forwards reverts
           *  There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
           * @param data The raw data to delegatecall
           * @return The returned bytes from the delegatecall
           */
          function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
              (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
              assembly {
                  if eq(success, 0) {
                      revert(add(returnData, 0x20), returndatasize)
                  }
              }
              return abi.decode(returnData, (bytes));
          }
      
          function delegateToViewAndReturn() private view returns (bytes memory) {
              (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
      
              assembly {
                  let free_mem_ptr := mload(0x40)
                  returndatacopy(free_mem_ptr, 0, returndatasize)
      
                  switch success
                  case 0 { revert(free_mem_ptr, returndatasize) }
                  default { return(add(free_mem_ptr, 0x40), sub(returndatasize, 0x40)) }
              }
          }
      
          function delegateAndReturn() private returns (bytes memory) {
              (bool success, ) = implementation.delegatecall(msg.data);
      
              assembly {
                  let free_mem_ptr := mload(0x40)
                  returndatacopy(free_mem_ptr, 0, returndatasize)
      
                  switch success
                  case 0 { revert(free_mem_ptr, returndatasize) }
                  default { return(free_mem_ptr, returndatasize) }
              }
          }
      
          /**
           * @notice Delegates execution to an implementation contract
           * @dev It returns to the external caller whatever the implementation returns or forwards reverts
           */
          function() external payable {
              require(msg.value == 0,"YAMDelegator:fallback: cannot send value to fallback");
      
              // delegate all other functions to current implementation
              delegateAndReturn();
          }
      }

      File 4 of 4: YAMDelegate3
      pragma solidity 0.5.15;
      
      /* Copyright 2020 Compound Labs, Inc.
      
      Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
      
      1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
      
      2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
      
      3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
      
      THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
      
      
      contract YAMGovernanceStorage {
          /// @notice A record of each accounts delegate
          mapping (address => address) internal _delegates;
      
          /// @notice A checkpoint for marking number of votes from a given block
          struct Checkpoint {
              uint32 fromBlock;
              uint256 votes;
          }
      
          /// @notice A record of votes checkpoints for each account, by index
          mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
      
          /// @notice The number of checkpoints for each account
          mapping (address => uint32) public numCheckpoints;
      
          /// @notice The EIP-712 typehash for the contract's domain
          bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
      
          /// @notice The EIP-712 typehash for the delegation struct used by the contract
          bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
      
          /// @notice A record of states for signing / validating signatures
          mapping (address => uint) public nonces;
      }
      
      /**
       * @dev Wrappers over Solidity's arithmetic operations with added overflow
       * checks.
       *
       * Arithmetic operations in Solidity wrap on overflow. This can easily result
       * in bugs, because programmers usually assume that an overflow raises an
       * error, which is the standard behavior in high level programming languages.
       * `SafeMath` restores this intuition by reverting the transaction when an
       * operation overflows.
       *
       * Using this library instead of the unchecked operations eliminates an entire
       * class of bugs, so it's recommended to use it always.
       */
      library SafeMath {
          /**
           * @dev Returns the addition of two unsigned integers, reverting on
           * overflow.
           *
           * Counterpart to Solidity's `+` operator.
           *
           * Requirements:
           *
           * - Addition cannot overflow.
           */
          function add(uint256 a, uint256 b) internal pure returns (uint256) {
              uint256 c = a + b;
              require(c >= a, "SafeMath: addition overflow");
      
              return c;
          }
      
          /**
           * @dev Returns the subtraction of two unsigned integers, reverting on
           * overflow (when the result is negative).
           *
           * Counterpart to Solidity's `-` operator.
           *
           * Requirements:
           *
           * - Subtraction cannot overflow.
           */
          function sub(uint256 a, uint256 b) internal pure returns (uint256) {
              return sub(a, b, "SafeMath: subtraction overflow");
          }
      
          /**
           * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
           * overflow (when the result is negative).
           *
           * Counterpart to Solidity's `-` operator.
           *
           * Requirements:
           *
           * - Subtraction cannot overflow.
           */
          function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
              require(b <= a, errorMessage);
              uint256 c = a - b;
      
              return c;
          }
      
          /**
           * @dev Returns the multiplication of two unsigned integers, reverting on
           * overflow.
           *
           * Counterpart to Solidity's `*` operator.
           *
           * Requirements:
           *
           * - Multiplication cannot overflow.
           */
          function mul(uint256 a, uint256 b) internal pure returns (uint256) {
              // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
              // benefit is lost if 'b' is also tested.
              // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
              if (a == 0) {
                  return 0;
              }
      
              uint256 c = a * b;
              require(c / a == b, "SafeMath: multiplication overflow");
      
              return c;
          }
      
          /**
           * @dev Returns the integer division of two unsigned integers. Reverts on
           * division by zero. The result is rounded towards zero.
           *
           * Counterpart to Solidity's `/` operator. Note: this function uses a
           * `revert` opcode (which leaves remaining gas untouched) while Solidity
           * uses an invalid opcode to revert (consuming all remaining gas).
           *
           * Requirements:
           *
           * - The divisor cannot be zero.
           */
          function div(uint256 a, uint256 b) internal pure returns (uint256) {
              return div(a, b, "SafeMath: division by zero");
          }
      
          /**
           * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
           * division by zero. The result is rounded towards zero.
           *
           * Counterpart to Solidity's `/` operator. Note: this function uses a
           * `revert` opcode (which leaves remaining gas untouched) while Solidity
           * uses an invalid opcode to revert (consuming all remaining gas).
           *
           * Requirements:
           *
           * - The divisor cannot be zero.
           */
          function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
              require(b > 0, errorMessage);
              uint256 c = a / b;
              // assert(a == b * c + a % b); // There is no case in which this doesn't hold
      
              return c;
          }
      
          /**
           * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
           * Reverts when dividing by zero.
           *
           * Counterpart to Solidity's `%` operator. This function uses a `revert`
           * opcode (which leaves remaining gas untouched) while Solidity uses an
           * invalid opcode to revert (consuming all remaining gas).
           *
           * Requirements:
           *
           * - The divisor cannot be zero.
           */
          function mod(uint256 a, uint256 b) internal pure returns (uint256) {
              return mod(a, b, "SafeMath: modulo by zero");
          }
      
          /**
           * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
           * Reverts with custom message when dividing by zero.
           *
           * Counterpart to Solidity's `%` operator. This function uses a `revert`
           * opcode (which leaves remaining gas untouched) while Solidity uses an
           * invalid opcode to revert (consuming all remaining gas).
           *
           * Requirements:
           *
           * - The divisor cannot be zero.
           */
          function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
              require(b != 0, errorMessage);
              return a % b;
          }
      }
      
      
      // Storage for a YAM token
      contract YAMTokenStorage {
      
          using SafeMath for uint256;
      
          /**
           * @dev Guard variable for re-entrancy checks. Not currently used
           */
          bool internal _notEntered;
      
          /**
           * @notice EIP-20 token name for this token
           */
          string public name;
      
          /**
           * @notice EIP-20 token symbol for this token
           */
          string public symbol;
      
          /**
           * @notice EIP-20 token decimals for this token
           */
          uint8 public decimals;
      
          /**
           * @notice Governor for this contract
           */
          address public gov;
      
          /**
           * @notice Pending governance for this contract
           */
          address public pendingGov;
      
          /**
           * @notice Approved rebaser for this contract
           */
          address public rebaser;
      
          /**
           * @notice Approved migrator for this contract
           */
          address public migrator;
      
          /**
           * @notice Incentivizer address of YAM protocol
           */
          address public incentivizer;
      
          /**
           * @notice Total supply of YAMs
           */
          uint256 public totalSupply;
      
          /**
           * @notice Internal decimals used to handle scaling factor
           */
          uint256 public constant internalDecimals = 10**24;
      
          /**
           * @notice Used for percentage maths
           */
          uint256 public constant BASE = 10**18;
      
          /**
           * @notice Scaling factor that adjusts everyone's balances
           */
          uint256 public yamsScalingFactor;
      
          mapping (address => uint256) internal _yamBalances;
      
          mapping (address => mapping (address => uint256)) internal _allowedFragments;
      
          uint256 public initSupply;
      
      
          // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
          bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
          bytes32 public DOMAIN_SEPARATOR;
      }
      
      contract YAMTokenInterface is YAMTokenStorage, YAMGovernanceStorage {
      
          /// @notice An event thats emitted when an account changes its delegate
          event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
      
          /// @notice An event thats emitted when a delegate account's vote balance changes
          event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
      
          /**
           * @notice Event emitted when tokens are rebased
           */
          event Rebase(uint256 epoch, uint256 prevYamsScalingFactor, uint256 newYamsScalingFactor);
      
          /*** Gov Events ***/
      
          /**
           * @notice Event emitted when pendingGov is changed
           */
          event NewPendingGov(address oldPendingGov, address newPendingGov);
      
          /**
           * @notice Event emitted when gov is changed
           */
          event NewGov(address oldGov, address newGov);
      
          /**
           * @notice Sets the rebaser contract
           */
          event NewRebaser(address oldRebaser, address newRebaser);
      
          /**
           * @notice Sets the migrator contract
           */
          event NewMigrator(address oldMigrator, address newMigrator);
      
          /**
           * @notice Sets the incentivizer contract
           */
          event NewIncentivizer(address oldIncentivizer, address newIncentivizer);
      
          /* - ERC20 Events - */
      
          /**
           * @notice EIP20 Transfer event
           */
          event Transfer(address indexed from, address indexed to, uint amount);
      
          /**
           * @notice EIP20 Approval event
           */
          event Approval(address indexed owner, address indexed spender, uint amount);
      
          /* - Extra Events - */
          /**
           * @notice Tokens minted event
           */
          event Mint(address to, uint256 amount);
      
          /**
           * @notice Tokens burned event
           */
          event Burn(address from, uint256 amount);
      
          // Public functions
          function transfer(address to, uint256 value) external returns(bool);
          function transferFrom(address from, address to, uint256 value) external returns(bool);
          function balanceOf(address who) external view returns(uint256);
          function balanceOfUnderlying(address who) external view returns(uint256);
          function allowance(address owner_, address spender) external view returns(uint256);
          function approve(address spender, uint256 value) external returns (bool);
          function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
          function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
          function maxScalingFactor() external view returns (uint256);
          function yamToFragment(uint256 yam) external view returns (uint256);
          function fragmentToYam(uint256 value) external view returns (uint256);
      
          /* - Governance Functions - */
          function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
          function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
          function delegate(address delegatee) external;
          function delegates(address delegator) external view returns (address);
          function getCurrentVotes(address account) external view returns (uint256);
      
          /* - Permissioned/Governance functions - */
          function mint(address to, uint256 amount) external returns (bool);
          function burn(uint256 amount) external returns (bool);
          function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256);
          function _setRebaser(address rebaser_) external;
          function _setIncentivizer(address incentivizer_) external;
          function _setPendingGov(address pendingGov_) external;
          function _acceptGov() external;
      }
      
      /* Copyright 2020 Compound Labs, Inc.
      
      Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
      
      1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
      
      2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
      
      3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
      
      THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
      
      
      
      contract YAMGovernanceToken is YAMTokenInterface {
      
            /// @notice An event thats emitted when an account changes its delegate
          event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
      
          /// @notice An event thats emitted when a delegate account's vote balance changes
          event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
      
          /**
           * @notice Get delegatee for an address delegating
           * @param delegator The address to get delegatee for
           */
          function delegates(address delegator)
              external
              view
              returns (address)
          {
              return _delegates[delegator];
          }
      
         /**
          * @notice Delegate votes from `msg.sender` to `delegatee`
          * @param delegatee The address to delegate votes to
          */
          function delegate(address delegatee) external {
              return _delegate(msg.sender, delegatee);
          }
      
          /**
           * @notice Delegates votes from signatory to `delegatee`
           * @param delegatee The address to delegate votes to
           * @param nonce The contract state required to match the signature
           * @param expiry The time at which to expire the signature
           * @param v The recovery byte of the signature
           * @param r Half of the ECDSA signature pair
           * @param s Half of the ECDSA signature pair
           */
          function delegateBySig(
              address delegatee,
              uint nonce,
              uint expiry,
              uint8 v,
              bytes32 r,
              bytes32 s
          )
              external
          {
              bytes32 structHash = keccak256(
                  abi.encode(
                      DELEGATION_TYPEHASH,
                      delegatee,
                      nonce,
                      expiry
                  )
              );
      
              bytes32 digest = keccak256(
                  abi.encodePacked(
                      "\x19\x01",
                      DOMAIN_SEPARATOR,
                      structHash
                  )
              );
      
              address signatory = ecrecover(digest, v, r, s);
              require(signatory != address(0), "YAM::delegateBySig: invalid signature");
              require(nonce == nonces[signatory]++, "YAM::delegateBySig: invalid nonce");
              require(now <= expiry, "YAM::delegateBySig: signature expired");
              return _delegate(signatory, delegatee);
          }
      
          /**
           * @notice Gets the current votes balance for `account`
           * @param account The address to get votes balance
           * @return The number of current votes for `account`
           */
          function getCurrentVotes(address account)
              external
              view
              returns (uint256)
          {
              uint32 nCheckpoints = numCheckpoints[account];
              return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
          }
      
          /**
           * @notice Determine the prior number of votes for an account as of a block number
           * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
           * @param account The address of the account to check
           * @param blockNumber The block number to get the vote balance at
           * @return The number of votes the account had as of the given block
           */
          function getPriorVotes(address account, uint blockNumber)
              external
              view
              returns (uint256)
          {
              require(blockNumber < block.number, "YAM::getPriorVotes: not yet determined");
      
              uint32 nCheckpoints = numCheckpoints[account];
              if (nCheckpoints == 0) {
                  return 0;
              }
      
              // First check most recent balance
              if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
                  return checkpoints[account][nCheckpoints - 1].votes;
              }
      
              // Next check implicit zero balance
              if (checkpoints[account][0].fromBlock > blockNumber) {
                  return 0;
              }
      
              uint32 lower = 0;
              uint32 upper = nCheckpoints - 1;
              while (upper > lower) {
                  uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
                  Checkpoint memory cp = checkpoints[account][center];
                  if (cp.fromBlock == blockNumber) {
                      return cp.votes;
                  } else if (cp.fromBlock < blockNumber) {
                      lower = center;
                  } else {
                      upper = center - 1;
                  }
              }
              return checkpoints[account][lower].votes;
          }
      
          function _delegate(address delegator, address delegatee)
              internal
          {
              address currentDelegate = _delegates[delegator];
              uint256 delegatorBalance = _yamBalances[delegator]; // balance of underlying YAMs (not scaled);
              _delegates[delegator] = delegatee;
      
              emit DelegateChanged(delegator, currentDelegate, delegatee);
      
              _moveDelegates(currentDelegate, delegatee, delegatorBalance);
          }
      
          function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
              if (srcRep != dstRep && amount > 0) {
                  if (srcRep != address(0)) {
                      // decrease old representative
                      uint32 srcRepNum = numCheckpoints[srcRep];
                      uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
                      uint256 srcRepNew = srcRepOld.sub(amount);
                      _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
                  }
      
                  if (dstRep != address(0)) {
                      // increase new representative
                      uint32 dstRepNum = numCheckpoints[dstRep];
                      uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
                      uint256 dstRepNew = dstRepOld.add(amount);
                      _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
                  }
              }
          }
      
          function _writeCheckpoint(
              address delegatee,
              uint32 nCheckpoints,
              uint256 oldVotes,
              uint256 newVotes
          )
              internal
          {
              uint32 blockNumber = safe32(block.number, "YAM::_writeCheckpoint: block number exceeds 32 bits");
      
              if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
                  checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
              } else {
                  checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
                  numCheckpoints[delegatee] = nCheckpoints + 1;
              }
      
              emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
          }
      
          function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
              require(n < 2**32, errorMessage);
              return uint32(n);
          }
      
          function getChainId() internal pure returns (uint) {
              uint256 chainId;
              assembly { chainId := chainid() }
              return chainId;
          }
      }
      
      /**
       * @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);
      }
      
      /**
       * @dev Collection of functions related to the address type
       */
      library Address {
          /**
           * @dev Returns true if `account` is a contract.
           *
           * [IMPORTANT]
           * ====
           * It is unsafe to assume that an address for which this function returns
           * false is an externally-owned account (EOA) and not a contract.
           *
           * Among others, `isContract` will return false for the following
           * types of addresses:
           *
           *  - an externally-owned account
           *  - a contract in construction
           *  - an address where a contract will be created
           *  - an address where a contract lived, but was destroyed
           * ====
           */
          function isContract(address account) internal view returns (bool) {
              // This method relies in extcodesize, which returns 0 for contracts in
              // construction, since the code is only stored at the end of the
              // constructor execution.
      
              uint256 size;
              // solhint-disable-next-line no-inline-assembly
              assembly { size := extcodesize(account) }
              return size > 0;
          }
      
          /**
           * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
           * `recipient`, forwarding all available gas and reverting on errors.
           *
           * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
           * of certain opcodes, possibly making contracts go over the 2300 gas limit
           * imposed by `transfer`, making them unable to receive funds via
           * `transfer`. {sendValue} removes this limitation.
           *
           * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
           *
           * IMPORTANT: because control is transferred to `recipient`, care must be
           * taken to not create reentrancy vulnerabilities. Consider using
           * {ReentrancyGuard} or the
           * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
           */
          function sendValue(address payable recipient, uint256 amount) internal {
              require(address(this).balance >= amount, "Address: insufficient balance");
      
              // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
              (bool success, ) = recipient.call.value(amount)("");
              require(success, "Address: unable to send value, recipient may have reverted");
          }
      
          /**
           * @dev Performs a Solidity function call using a low level `call`. A
           * plain`call` is an unsafe replacement for a function call: use this
           * function instead.
           *
           * If `target` reverts with a revert reason, it is bubbled up by this
           * function (like regular Solidity function calls).
           *
           * Returns the raw returned data. To convert to the expected return value,
           * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
           *
           * Requirements:
           *
           * - `target` must be a contract.
           * - calling `target` with `data` must not revert.
           *
           * _Available since v3.1._
           */
          function functionCall(address target, bytes memory data) internal returns (bytes memory) {
            return functionCall(target, data, "Address: low-level call failed");
          }
      
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
           * `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
              return _functionCallWithValue(target, data, 0, errorMessage);
          }
      
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but also transferring `value` wei to `target`.
           *
           * Requirements:
           *
           * - the calling contract must have an ETH balance of at least `value`.
           * - the called Solidity function must be `payable`.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
              return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
          }
      
          /**
           * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
           * with `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
              require(address(this).balance >= value, "Address: insufficient balance for call");
              return _functionCallWithValue(target, data, value, errorMessage);
          }
      
          function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
              require(isContract(target), "Address: call to non-contract");
      
              // solhint-disable-next-line avoid-low-level-calls
              (bool success, bytes memory returndata) = target.call.value(weiValue)(data);
              if (success) {
                  return returndata;
              } else {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
      
                      // solhint-disable-next-line no-inline-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
      }
      
      /**
       * @title SafeERC20
       * @dev Wrappers around ERC20 operations that throw on failure (when the token
       * contract returns false). Tokens that return no value (and instead revert or
       * throw on failure) are also supported, non-reverting calls are assumed to be
       * successful.
       * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
       * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
       */
      library SafeERC20 {
          using SafeMath for uint256;
          using Address for address;
      
          function safeTransfer(IERC20 token, address to, uint256 value) internal {
              _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
          }
      
          function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
              _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
          }
      
          /**
           * @dev Deprecated. This function has issues similar to the ones found in
           * {IERC20-approve}, and its usage is discouraged.
           *
           * Whenever possible, use {safeIncreaseAllowance} and
           * {safeDecreaseAllowance} instead.
           */
          function safeApprove(IERC20 token, address spender, uint256 value) internal {
              // safeApprove should only be called when setting an initial allowance,
              // or when resetting it to zero. To increase and decrease it, use
              // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
              // solhint-disable-next-line max-line-length
              require((value == 0) || (token.allowance(address(this), spender) == 0),
                  "SafeERC20: approve from non-zero to non-zero allowance"
              );
              _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
          }
      
          function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
              uint256 newAllowance = token.allowance(address(this), spender).add(value);
              _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
          }
      
          function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
              uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
              _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
          }
      
          /**
           * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
           * on the return value: the return value is optional (but if data is returned, it must not be false).
           * @param token The token targeted by the call.
           * @param data The call data (encoded using abi.encode or one of its variants).
           */
          function _callOptionalReturn(IERC20 token, bytes memory data) private {
              // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
              // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
              // the target address contains contract code and also asserts for success in the low-level call.
      
              bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
              if (returndata.length > 0) { // Return data is optional
                  // solhint-disable-next-line max-line-length
                  require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
              }
          }
      }
      
      contract YAMToken is YAMGovernanceToken {
          // Modifiers
          modifier onlyGov() {
              require(msg.sender == gov);
              _;
          }
      
          modifier onlyRebaser() {
              require(msg.sender == rebaser);
              _;
          }
      
          modifier onlyMinter() {
              require(
                  msg.sender == rebaser
                  || msg.sender == gov
                  || msg.sender == incentivizer
                  || msg.sender == migrator,
                  "not minter"
              );
              _;
          }
      
          modifier validRecipient(address to) {
              require(to != address(0x0));
              require(to != address(this));
              _;
          }
      
          function initialize(
              string memory name_,
              string memory symbol_,
              uint8 decimals_
          )
              public
          {
              require(yamsScalingFactor == 0, "already initialized");
              name = name_;
              symbol = symbol_;
              decimals = decimals_;
          }
      
      
          /**
          * @notice Computes the current max scaling factor
          */
          function maxScalingFactor()
              external
              view
              returns (uint256)
          {
              return _maxScalingFactor();
          }
      
          function _maxScalingFactor()
              internal
              view
              returns (uint256)
          {
              // scaling factor can only go up to 2**256-1 = initSupply * yamsScalingFactor
              // this is used to check if yamsScalingFactor will be too high to compute balances when rebasing.
              return uint256(-1) / initSupply;
          }
      
          /**
          * @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
          * @dev Limited to onlyMinter modifier
          */
          function mint(address to, uint256 amount)
              external
              onlyMinter
              returns (bool)
          {
              _mint(to, amount);
              return true;
          }
      
          function _mint(address to, uint256 amount)
              internal
          {
            if (msg.sender == migrator) {
              // migrator directly uses v2 balance for the amount
      
              // increase initSupply
              initSupply = initSupply.add(amount);
      
              // get external value
              uint256 scaledAmount = _yamToFragment(amount);
      
              // increase totalSupply
              totalSupply = totalSupply.add(scaledAmount);
      
              // make sure the mint didnt push maxScalingFactor too low
              require(yamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
      
              // add balance
              _yamBalances[to] = _yamBalances[to].add(amount);
      
              // add delegates to the minter
              _moveDelegates(address(0), _delegates[to], amount);
              emit Mint(to, scaledAmount);
              emit Transfer(address(0), to, scaledAmount);
            } else {
              // increase totalSupply
              totalSupply = totalSupply.add(amount);
      
              // get underlying value
              uint256 yamValue = _fragmentToYam(amount);
      
              // increase initSupply
              initSupply = initSupply.add(yamValue);
      
              // make sure the mint didnt push maxScalingFactor too low
              require(yamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
      
              // add balance
              _yamBalances[to] = _yamBalances[to].add(yamValue);
      
              // add delegates to the minter
              _moveDelegates(address(0), _delegates[to], yamValue);
              emit Mint(to, amount);
              emit Transfer(address(0), to, amount);
            }
          }
      
          /**
          * @notice Burns tokens from msg.sender, decreases totalSupply, initSupply, and a users balance.
          */
      
          function burn(uint256 amount)
              external
              returns (bool)
          {
              _burn(amount);
              return true;
          }
      
          function _burn(uint256 amount)
              internal
          {
                      // decrease totalSupply
              totalSupply = totalSupply.sub(amount);
      
              // get underlying value
              uint256 yamValue = _fragmentToYam(amount);
      
              // decrease initSupply
              initSupply = initSupply.sub(yamValue);
      
              // decrease balance
              _yamBalances[msg.sender] = _yamBalances[msg.sender].sub(yamValue);
      
              // add delegates to the minter
              _moveDelegates(_delegates[msg.sender], address(0), yamValue);
              emit Burn(msg.sender, amount);
              emit Transfer(msg.sender, address(0), amount);
              }
      
          /**
          * @notice Mints new tokens using underlying amount, increasing totalSupply, initSupply, and a users balance.
          * @dev Limited to onlyMinter modifier
          */
          function mintUnderlying(address to, uint256 amount)
              external
              onlyMinter
              returns (bool)
          {
              _mintUnderlying(to, amount);
              return true;
          }
      
          function _mintUnderlying(address to, uint256 amount)
              internal
          {
      
              // increase initSupply
              initSupply = initSupply.add(amount);
      
              // get external value
              uint256 scaledAmount = _yamToFragment(amount);
      
              // increase totalSupply
              totalSupply = totalSupply.add(scaledAmount);
      
              // make sure the mint didnt push maxScalingFactor too low
              require(yamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
      
              // add balance
              _yamBalances[to] = _yamBalances[to].add(amount);
      
              // add delegates to the minter
              _moveDelegates(address(0), _delegates[to], amount);
              emit Mint(to, scaledAmount);
              emit Transfer(address(0), to, scaledAmount);
         
          }
      
          /**
           * @dev Transfer underlying balance to a specified address.
           * @param to The address to transfer to.
           * @param value The amount to be transferred.
           * @return True on success, false otherwise.
           */
          function transferUnderlying(address to, uint256 value)
              external
              validRecipient(to)
              returns (bool)
          {
              // sub from balance of sender
              _yamBalances[msg.sender] = _yamBalances[msg.sender].sub(value);
      
              // add to balance of receiver
              _yamBalances[to] = _yamBalances[to].add(value);
              emit Transfer(msg.sender, to, _yamToFragment(value));
      
              _moveDelegates(_delegates[msg.sender], _delegates[to], value);
              return true;
          }
          
          /* - ERC20 functionality - */
      
          /**
          * @dev Transfer tokens to a specified address.
          * @param to The address to transfer to.
          * @param value The amount to be transferred.
          * @return True on success, false otherwise.
          */
          function transfer(address to, uint256 value)
              external
              validRecipient(to)
              returns (bool)
          {
              // underlying balance is stored in yams, so divide by current scaling factor
      
              // note, this means as scaling factor grows, dust will be untransferrable.
              // minimum transfer value == yamsScalingFactor / 1e24;
      
              // get amount in underlying
              uint256 yamValue = _fragmentToYam(value);
      
              // sub from balance of sender
              _yamBalances[msg.sender] = _yamBalances[msg.sender].sub(yamValue);
      
              // add to balance of receiver
              _yamBalances[to] = _yamBalances[to].add(yamValue);
              emit Transfer(msg.sender, to, value);
      
              _moveDelegates(_delegates[msg.sender], _delegates[to], yamValue);
              return true;
          }
      
          /**
          * @dev Transfer tokens from one address to another.
          * @param from The address you want to send tokens from.
          * @param to The address you want to transfer to.
          * @param value The amount of tokens to be transferred.
          */
          function transferFrom(address from, address to, uint256 value)
              external
              validRecipient(to)
              returns (bool)
          {
              // decrease allowance
              _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
      
              // get value in yams
              uint256 yamValue = _fragmentToYam(value);
      
              // sub from from
              _yamBalances[from] = _yamBalances[from].sub(yamValue);
              _yamBalances[to] = _yamBalances[to].add(yamValue);
              emit Transfer(from, to, value);
      
              _moveDelegates(_delegates[from], _delegates[to], yamValue);
              return true;
          }
      
          /**
          * @param who The address to query.
          * @return The balance of the specified address.
          */
          function balanceOf(address who)
            external
            view
            returns (uint256)
          {
            return _yamToFragment(_yamBalances[who]);
          }
      
          /** @notice Currently returns the internal storage amount
          * @param who The address to query.
          * @return The underlying balance of the specified address.
          */
          function balanceOfUnderlying(address who)
            external
            view
            returns (uint256)
          {
            return _yamBalances[who];
          }
      
          /**
           * @dev Function to check the amount of tokens that an owner has allowed to a spender.
           * @param owner_ The address which owns the funds.
           * @param spender The address which will spend the funds.
           * @return The number of tokens still available for the spender.
           */
          function allowance(address owner_, address spender)
              external
              view
              returns (uint256)
          {
              return _allowedFragments[owner_][spender];
          }
      
          /**
           * @dev Approve the passed address to spend the specified amount of tokens on behalf of
           * msg.sender. This method is included for ERC20 compatibility.
           * increaseAllowance and decreaseAllowance should be used instead.
           * Changing an allowance with this method brings the risk that someone may transfer both
           * the old and the new allowance - if they are both greater than zero - if a transfer
           * transaction is mined before the later approve() call is mined.
           *
           * @param spender The address which will spend the funds.
           * @param value The amount of tokens to be spent.
           */
          function approve(address spender, uint256 value)
              external
              returns (bool)
          {
              _allowedFragments[msg.sender][spender] = value;
              emit Approval(msg.sender, spender, value);
              return true;
          }
      
          /**
           * @dev Increase the amount of tokens that an owner has allowed to a spender.
           * This method should be used instead of approve() to avoid the double approval vulnerability
           * described above.
           * @param spender The address which will spend the funds.
           * @param addedValue The amount of tokens to increase the allowance by.
           */
          function increaseAllowance(address spender, uint256 addedValue)
              external
              returns (bool)
          {
              _allowedFragments[msg.sender][spender] =
                  _allowedFragments[msg.sender][spender].add(addedValue);
              emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
              return true;
          }
      
          /**
           * @dev Decrease the amount of tokens that an owner has allowed to a spender.
           *
           * @param spender The address which will spend the funds.
           * @param subtractedValue The amount of tokens to decrease the allowance by.
           */
          function decreaseAllowance(address spender, uint256 subtractedValue)
              external
              returns (bool)
          {
              uint256 oldValue = _allowedFragments[msg.sender][spender];
              if (subtractedValue >= oldValue) {
                  _allowedFragments[msg.sender][spender] = 0;
              } else {
                  _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
              }
              emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
              return true;
          }
      
      
          // --- Approve by signature ---
          function permit(
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          )
              external
          {
              require(now <= deadline, "YAM/permit-expired");
      
              bytes32 digest =
                  keccak256(
                      abi.encodePacked(
                          "\x19\x01",
                          DOMAIN_SEPARATOR,
                          keccak256(
                              abi.encode(
                                  PERMIT_TYPEHASH,
                                  owner,
                                  spender,
                                  value,
                                  nonces[owner]++,
                                  deadline
                              )
                          )
                      )
                  );
      
              require(owner != address(0), "YAM/invalid-address-0");
              require(owner == ecrecover(digest, v, r, s), "YAM/invalid-permit");
              _allowedFragments[owner][spender] = value;
              emit Approval(owner, spender, value);
          }
      
          /* - Governance Functions - */
      
          /** @notice sets the rebaser
           * @param rebaser_ The address of the rebaser contract to use for authentication.
           */
          function _setRebaser(address rebaser_)
              external
              onlyGov
          {
              address oldRebaser = rebaser;
              rebaser = rebaser_;
              emit NewRebaser(oldRebaser, rebaser_);
          }
      
          /** @notice sets the migrator
           * @param migrator_ The address of the migrator contract to use for authentication.
           */
          function _setMigrator(address migrator_)
              external
              onlyGov
          {
              address oldMigrator = migrator_;
              migrator = migrator_;
              emit NewMigrator(oldMigrator, migrator_);
          }
      
          /** @notice sets the incentivizer
           * @param incentivizer_ The address of the rebaser contract to use for authentication.
           */
          function _setIncentivizer(address incentivizer_)
              external
              onlyGov
          {
              address oldIncentivizer = incentivizer;
              incentivizer = incentivizer_;
              emit NewIncentivizer(oldIncentivizer, incentivizer_);
          }
      
          /** @notice sets the pendingGov
           * @param pendingGov_ The address of the rebaser contract to use for authentication.
           */
          function _setPendingGov(address pendingGov_)
              external
              onlyGov
          {
              address oldPendingGov = pendingGov;
              pendingGov = pendingGov_;
              emit NewPendingGov(oldPendingGov, pendingGov_);
          }
      
          /** @notice allows governance to assign delegate to self
           *
           */
          function _acceptGov()
              external
          {
              require(msg.sender == pendingGov, "!pending");
              address oldGov = gov;
              gov = pendingGov;
              pendingGov = address(0);
              emit NewGov(oldGov, gov);
          }
      
          function assignSelfDelegate(address nonvotingContract)
              external
              onlyGov
          {
              address delegate = _delegates[nonvotingContract];
              require( delegate == address(0), "!address(0)" );
              // assigns delegate to self only
              _delegate(nonvotingContract, nonvotingContract);
          }
      
          /* - Extras - */
      
          /**
          * @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
          *
          * @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
          *      Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
          *      and targetRate is CpiOracleRate / baseCpi
          */
          function rebase(
              uint256 epoch,
              uint256 indexDelta,
              bool positive
          )
              external
              onlyRebaser
              returns (uint256)
          {
              // no change
              if (indexDelta == 0) {
                emit Rebase(epoch, yamsScalingFactor, yamsScalingFactor);
                return totalSupply;
              }
      
              // for events
              uint256 prevYamsScalingFactor = yamsScalingFactor;
      
      
              if (!positive) {
                  // negative rebase, decrease scaling factor
                  yamsScalingFactor = yamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
              } else {
                  // positive reabse, increase scaling factor
                  uint256 newScalingFactor = yamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
                  if (newScalingFactor < _maxScalingFactor()) {
                      yamsScalingFactor = newScalingFactor;
                  } else {
                      yamsScalingFactor = _maxScalingFactor();
                  }
              }
      
              // update total supply, correctly
              totalSupply = _yamToFragment(initSupply);
      
              emit Rebase(epoch, prevYamsScalingFactor, yamsScalingFactor);
              return totalSupply;
          }
      
          function yamToFragment(uint256 yam)
              external
              view
              returns (uint256)
          {
              return _yamToFragment(yam);
          }
      
          function fragmentToYam(uint256 value)
              external
              view
              returns (uint256)
          {
              return _fragmentToYam(value);
          }
      
          function _yamToFragment(uint256 yam)
              internal
              view
              returns (uint256)
          {
              return yam.mul(yamsScalingFactor).div(internalDecimals);
          }
      
          function _fragmentToYam(uint256 value)
              internal
              view
              returns (uint256)
          {
              return value.mul(internalDecimals).div(yamsScalingFactor);
          }
      
          // Rescue tokens
          function rescueTokens(
              address token,
              address to,
              uint256 amount
          )
              external
              onlyGov
              returns (bool)
          {
              // transfer to
              SafeERC20.safeTransfer(IERC20(token), to, amount);
              return true;
          }
      }
      
      contract YAMLogic3 is YAMToken {
          /**
           * @notice Initialize the new money market
           * @param name_ ERC-20 name of this token
           * @param symbol_ ERC-20 symbol of this token
           * @param decimals_ ERC-20 decimal precision of this token
           */
          function initialize(
              string memory name_,
              string memory symbol_,
              uint8 decimals_,
              address initial_owner,
              uint256 initTotalSupply_
          )
              public
          {
              super.initialize(name_, symbol_, decimals_);
      
              yamsScalingFactor = BASE;
              initSupply = _fragmentToYam(initTotalSupply_);
              totalSupply = initTotalSupply_;
              _yamBalances[initial_owner] = initSupply;
      
              DOMAIN_SEPARATOR = keccak256(
                  abi.encode(
                      DOMAIN_TYPEHASH,
                      keccak256(bytes(name)),
                      getChainId(),
                      address(this)
                  )
              );
          }
      }
      
      /* Copyright 2020 Compound Labs, Inc.
      
      Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
      
      1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
      
      2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
      
      3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
      
      THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
      
      
      contract YAMDelegationStorage {
          /**
           * @notice Implementation address for this contract
           */
          address public implementation;
      }
      
      contract YAMDelegatorInterface is YAMDelegationStorage {
          /**
           * @notice Emitted when implementation is changed
           */
          event NewImplementation(address oldImplementation, address newImplementation);
      
          /**
           * @notice Called by the gov to update the implementation of the delegator
           * @param implementation_ The address of the new implementation for delegation
           * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
           * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
           */
          function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
      }
      
      contract YAMDelegateInterface is YAMDelegationStorage {
          /**
           * @notice Called by the delegator on a delegate to initialize it for duty
           * @dev Should revert if any issues arise which make it unfit for delegation
           * @param data The encoded bytes data for any initialization
           */
          function _becomeImplementation(bytes memory data) public;
      
          /**
           * @notice Called by the delegator on a delegate to forfeit its responsibility
           */
          function _resignImplementation() public;
      }
      
      
      contract YAMDelegate3 is YAMLogic3, YAMDelegateInterface {
          /**
           * @notice Construct an empty delegate
           */
          constructor() public {}
      
          /**
           * @notice Called by the delegator on a delegate to initialize it for duty
           * @param data The encoded bytes data for any initialization
           */
          function _becomeImplementation(bytes memory data) public {
              // Shh -- currently unused
              data;
      
              // Shh -- we don't ever want this hook to be marked pure
              if (false) {
                  implementation = address(0);
              }
      
              require(msg.sender == gov, "only the gov may call _becomeImplementation");
          }
      
          /**
           * @notice Called by the delegator on a delegate to forfeit its responsibility
           */
          function _resignImplementation() public {
              // Shh -- we don't ever want this hook to be marked pure
              if (false) {
                  implementation = address(0);
              }
      
              require(msg.sender == gov, "only the gov may call _resignImplementation");
          }
      }