Перейти к содержимому
Проверенный контрактТочноеMIT

RewardFarmers

Адрес0x6e16d88ea1dc719987dcf98bca4f2cb8282ce9e8
Баланс

0,057317 ETH

 

Транзакций

462

 

Компилятор

solc 0.8.12

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.12+commit.f00d7308
Язык
solidity
Оптимизация
Нет
Версия EVM
london
Лицензия
MIT
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
19 687 444
Транзакция создания
0x57838cf26d…1848a3ad9c

project:/contracts/RewardFarmers.sol

// contracts/RewardFarmers.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;

import "./Oracle.sol";
import "./libraries/ERC20Helpers.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";


/**
 *  
 *   .d8888b.  d8b                        888           .d8888b.                  d8b                                       
 *  d88P  Y88b Y8P                        888          d88P  Y88b                 Y8P                                       
 *  Y88b.                                 888          888    888                                                           
 *   "Y888b.   888 88888b.d88b.  88888b.  888  .d88b.  888        888d888 8888b.  888 88888b.       .d88b.  888d888 .d88b.  
 *      "Y88b. 888 888 "888 "88b 888 "88b 888 d8P  Y8b 888  88888 888P"      "88b 888 888 "88b     d88""88b 888P"  d88P"88b 
 *        "888 888 888  888  888 888  888 888 88888888 888    888 888    .d888888 888 888  888     888  888 888    888  888 
 *  Y88b  d88P 888 888  888  888 888 d88P 888 Y8b.     Y88b  d88P 888    888  888 888 888  888 d8b Y88..88P 888    Y88b 888 
 *   "Y8888P"  888 888  888  888 88888P"  888  "Y8888   "Y8888P88 888    "Y888888 888 888  888 Y8P  "Y88P"  888     "Y88888 
 *                               888                                                                                    888 
 *                               888                                                                               Y8b d88P 
 *                               888                                                                                "Y88P"  
 */


/// @title RewardFarmers
/// @notice A contract that allows users to stake a specific ERC20 token and earn rewards in other ERC20 tokens. Forked from shibalaunch
contract RewardFarmers is 
  Context, Ownable,
  ReentrancyGuard
{

  struct RewardInfo {
    uint256 id;
    string name;
    address token;
    string symbol;
    bool hasClaimed;
    uint256 decimals;
    uint256 canClaim;
    uint256 ethPerToken;
    uint256 totalRewards;
    uint256 distributionId;
  }

  struct UncommonReward {
    mapping(address => bool) hasClaimed;
    uint256 distributionId;
    uint256 perDeposit;
    uint256 amount;
    ERC20 token;
    uint256 id;
  }

  ERC20 public immutable Stakeable;
  address[] public commonRewardTokens;
  UncommonReward[] public uncommonRewards;
  Oracle public oracle;

  uint256 public totalStaked;
  mapping(address => uint256) public deposits;
  mapping(address => uint256) public lockedUntil;
  mapping(address => bool) public isCommonReward;
  mapping(address => mapping(address => uint256)) public nullifiedRewards;


  mapping(address => uint256) public userWithdrewEverythingAt;
  mapping(address => uint256) public rewardsPerDeposit;
  mapping(address => uint256) public totalRewarded;

  // depositForReward[uncommonRewardId][user] => depositAmount each
  // each time an uncommon reward is added, uncommonRewardId is increased.
  // This is a mapping from that index, to the deposits for a specific user.
  // If the deposit amount is type(uint256).max, that repesents have a 0 deposit for
  // the specified reward. If the deposit amount is 0, then it represents not
  // having any change in state while the uncommon rewardID is in the value specified.
  mapping(uint256 => mapping(address => uint256)) public depositForReward;

  mapping(address => bool) public isRewarder;
  bool public canChangeRewarder = true;
  uint256 public precision = 10 ** 22;
  uint256 public lockTime;

  /// @notice Initializes the contract with the stakeable token, lock time, and initial reward tokens.
  /// @param _stakeable The token that users can stake.
  /// @param _lockTime The time that users must wait after unlocking their stake before they can withdraw it.
  /// @param _rewardTokens An array of tokens that users can earn as rewards.
  constructor(Oracle _oracle, address _stakeable, uint256 _lockTime, address[] memory _rewardTokens) {
    Stakeable = ERC20(_stakeable);
    lockTime = _lockTime;
    oracle = _oracle;

    ensureRewardToken(address(0));
    for (uint16 i=0; i < _rewardTokens.length; i++)
      ensureRewardToken(_rewardTokens[i]);

    // making a call to common claimable to ensure that it can be called
    // and all of the chosen tokens exist. 
    commonClaimable(address(0));
  }

  // @notice Revoke ability to change the rewarder address
  function revokeSettingRewarder() public onlyOwner() {
    canChangeRewarder = false;
  }

  /// @notice Set a new rewarder for adding rewards
  /// @param _rewarderAddress The new rewarder contract address.
  /// @param _isRewarder boolean value correlated to if rewarder or not
  function setRewarderAddress(address _rewarderAddress, bool _isRewarder) public onlyOwner() {
    require(canChangeRewarder, 'Can not change rewarder address');
    isRewarder[_rewarderAddress] = _isRewarder;
  }

  /// @notice Set a new oracle for fetching token price data.
  /// @param _oracle The new oracle contract address.
  function setOracle(Oracle _oracle) external onlyOwner() {
    oracle = _oracle;
  }

  /// @notice Deposit stakeable tokens into the contract to start earning rewards.
  /// @param amount The amount of the stakeable token to deposit.
  function deposit(uint256 amount) external nonReentrant {
    require(!unlockInitiated(msg.sender), "you must wait until you withdraw your tokens");
    require(amount > 0, "you can not deposit 0 tokens");

    // Stakeable.transferFrom(msg.sender, address(this), amount);
    ERC20Helpers.safeTransferFrom(address(Stakeable), msg.sender, address(this), amount);

    // Claims all rewards before updating the user's stake.
    claimAllCommon(commonRewardTokens);

    totalStaked += amount;
    deposits[msg.sender] += amount;
    depositForReward[uncommonRewards.length][msg.sender] = deposits[msg.sender];

    userWithdrewEverythingAt[msg.sender] = 0;
  }

  /// @notice Withdraw all stakeable tokens from the contract.
  function withdrawAll() external {
    withdraw(deposits[msg.sender]);
  }

  /// @notice Withdraw a specific amount of stakeable tokens from the contract.
  /// @param amount The amount of stakeable tokens to withdraw.
  function withdraw(uint256 amount) public nonReentrant {
    require(unlockInitiated(msg.sender), "you must unlock your staked tokens first");
    require(isUnlocked(msg.sender), "your staked tokens are still locked");

    deposits[msg.sender] -= amount;
    totalStaked += deposits[msg.sender];

    ERC20Helpers.safeTransfer(address(Stakeable), msg.sender, amount);

    if (deposits[msg.sender] == 0) {
      depositForReward[uncommonRewards.length][msg.sender] = type(uint256).max;
      userWithdrewEverythingAt[msg.sender] = uncommonRewards.length + 1; // using 
    } else depositForReward[uncommonRewards.length][msg.sender] = deposits[msg.sender];

    lockedUntil[msg.sender] = 0;
  }

  /// @notice Initiates the process for unlocking the staked tokens.
  function unlock() external nonReentrant {
    require(!unlockInitiated(msg.sender), "Unlock is already pending");

    // Claims all rewards before updating the user's stake.
    claimAllCommon(commonRewardTokens);

    totalStaked -= deposits[msg.sender];
    lockedUntil[msg.sender] = block.timestamp + lockTime;
    depositForReward[uncommonRewards.length][msg.sender] = type(uint256).max;
  }

  /// @notice Internal function to nullify the rewards for a specific token.
  /// @param token The address of the token for which to nullify rewards.
  function nullifyRewardsForToken(address token) internal {
    nullifiedRewards[token][msg.sender] = rewardsPerDeposit[token];
  }

  /// @notice Get the number of uncommon rewards available.
  /// @return The count of uncommon rewards.
  function uncommonRewardCount() public view returns (uint256) {
    return uncommonRewards.length;
  }

  /// @notice Add rewards to the contract which can be claimed by stakers.
  /// @param distributionId The identifier for the reward distribution.
  /// @param token The address of the token in which rewards are being added.
  /// @param amount The amount of rewards to add.
  function addRewards(uint256 distributionId, address token, uint256 amount) external payable nonReentrant {
    require(isRewarder[msg.sender], "Can only be called from a rewarder address");
    require(totalStaked > 0, "can not add rewards if there are no stakers");

    if (token != address(0))
      ERC20Helpers.safeTransferFrom(token, msg.sender, address(this), amount);
    else amount = msg.value;

    if (isCommonReward[token]) {
      rewardsPerDeposit[token] += precision * amount / totalStaked;
      totalRewarded[token] += amount;
    } else {
      uncommonRewards.push();

      // Calculate the index of the new UncommonReward
      uint256 newIndex = uncommonRewards.length - 1;

      // Now, set the values for the new UncommonReward directly in storage.
      UncommonReward storage reward = uncommonRewards[newIndex];
      reward.perDeposit = precision * amount / totalStaked;
      reward.distributionId = distributionId;
      reward.id = newIndex; // Assuming ID is meant to be the index in the array
      reward.token = ERC20(token);
      reward.amount = amount;
    }
  }

  /// @notice Get general information about the contract's state and a user's stake.
  /// @param user The address of the user to retrieve information for.
  /// @return Total staked, user's deposit, lock status, and related token information.
  function getInfo(address user) external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
    return (
      totalStaked,
      deposits[user],
      lockedUntil[user],
      Stakeable.decimals(),
      Stakeable.balanceOf(user),
      ethPerToken(address(Stakeable)),
      Stakeable.allowance(user, address(this))
    );
  }

  /// @notice Get claimable uncommon rewards information for a user.
  /// @param user The address of the user to retrieve information for.
  /// @param page The page of the reward listing.
  /// @param pageSize The number of reward items per page.
  /// @return An array of RewardInfo structures containing reward details.
  function uncommonClaimable(address user, uint page, uint pageSize) external view returns (RewardInfo[] memory) {
    uint256 totalRewards = uncommonRewards.length;
    uint256 start = totalRewards > page * pageSize ? totalRewards - page * pageSize : 0;
    uint256 end = start + pageSize > totalRewards ? totalRewards : start + pageSize;
    uint256 count = end > start ? end - start : 0;

    RewardInfo[] memory rewards = new RewardInfo[](count);

    for (uint256 i = start; i < end; i++) {
      UncommonReward storage reward = uncommonRewards[i];
      ERC20 token = reward.token;
      rewards[i - start] = RewardInfo({
        id: reward.id,
        token: address(token),
        totalRewards: reward.amount,
        canClaim: rewardAmount(i, user),
        name: ERC20Helpers.tryName(token),
        hasClaimed: reward.hasClaimed[user],
        symbol: ERC20Helpers.trySymbol(token),
        distributionId: reward.distributionId,
        ethPerToken: ethPerToken(address(token)),
        decimals: ERC20Helpers.tryDecimals(token)
      });
    }

    return rewards;
  }

  /// @notice Get claimable common rewards information for a user.
  /// @param user The address of the user to retrieve information for.
  /// @return An array of RewardInfo structures containing reward details.
  function commonClaimable(address user) public view returns (RewardInfo[] memory) {
    address[] memory tokens = commonRewardTokens;
    RewardInfo[] memory rewards = new RewardInfo[](tokens.length);

    for (uint256 i = 0; i < tokens.length; i++) {
      uint256 decimals;
      string memory name;
      string memory symbol;
      if (tokens[i] == address(0)) {
        name = "Ethereum";
        symbol = "ETH";
        decimals = 18;
      } else {
        ERC20 token = ERC20(tokens[i]);

        name = ERC20Helpers.tryName(token);
        symbol = ERC20Helpers.trySymbol(token);
        decimals = ERC20Helpers.tryDecimals(token);
      }

      rewards[i] = RewardInfo({
        id: i,
        name: name,
        symbol: symbol,
        token: tokens[i],
        hasClaimed: false,
        distributionId: 0,
        decimals: decimals,
        canClaim: claimable(tokens[i], user),
        totalRewards: totalRewarded[tokens[i]],
        ethPerToken: ethPerToken(tokens[i])
      });
    }

    return rewards;
  }


  /// @notice Calculate the amount of a specific token that a user can claim as rewards.
  /// @param token The token to calculate claimable rewards for.
  /// @param user The user to calculate rewards for.
  /// @return The amount of the token that can be claimed.
  function claimable(address token, address user) public view returns (uint256){
    if (unlockInitiated(user)) return 0;

    return deposits[user] * (rewardsPerDeposit[token] - nullifiedRewards[token][user]) / precision;
  }

  /// @notice Calculate the amount of an uncommon reward that belongs to a user.
  /// @param uncommonRewardId The identifier for the uncommon reward.
  /// @param user The user for whom to calculate the reward amount.
  /// @return The amount of the reward that can be claimed.
  function rewardAmount(uint256 uncommonRewardId, address user) public view returns (uint256){
    UncommonReward storage reward = uncommonRewards[uncommonRewardId];
    uint256 deposited = userDepositAtTimeOfUncommonReward(uncommonRewardId, user);
    return deposited * reward.perDeposit / precision;
  }

  /// @notice Calculate the user's deposit amount at the time of an uncommon reward.
  /// @param uncommonRewardId The identifier for the uncommon reward.
  /// @param user The user for whom to calculate the deposit amount.
  /// @return The deposit amount at the time of the uncommon reward.
  function userDepositAtTimeOfUncommonReward(uint256 uncommonRewardId, address user) public view returns (uint256) {
    if (userWithdrewEverythingAt[user] == 0 && deposits[user] == 0)
      return 0; // User never deposited

    if (userWithdrewEverythingAt[user] != 0 && userWithdrewEverythingAt[user] <= uncommonRewardId + 1)
      return 0; // User withdrew everything before reward was added

    for (uint256 index = 0; index <= uncommonRewardId; index++)
      if (depositForReward[uncommonRewardId - index][user] > 0) {
        uint256 deposited = depositForReward[uncommonRewardId - index][user];
        if (deposited == type(uint256).max) return 0;
        else return deposited;
      }

    return 0; // user never deposited
  }

  /// @notice Internal function to allow a user to claim a specific uncommon reward.
  /// @param rewardId The identifier for the uncommon reward to claim.
  function claimUncommonReward(uint256 rewardId) internal {
    UncommonReward storage reward = uncommonRewards[rewardId];
    if (!reward.hasClaimed[msg.sender]) {
      reward.hasClaimed[msg.sender] = true;
      uint256 willClaim = rewardAmount(rewardId, msg.sender);

      if (willClaim > 0)
        ERC20Helpers.safeTransfer(address(reward.token), msg.sender, willClaim);
    }
  }

  /// @notice Internal function to allow a user to claim rewards in a specific token.
  /// @param token The token in which to claim rewards.
  function claim(address token) internal {
    uint256 willClaim = claimable(token, msg.sender);
    nullifyRewardsForToken(token);

    if (willClaim > 0) {
      if (token == address(0))
        payable(msg.sender).transfer(willClaim);
      else ERC20Helpers.safeTransfer(token, msg.sender, willClaim);
    }
  }

	/// @notice Internal function to claim all common rewards for a user.
	/// @param rewards An array of token addresses to claim rewards in.
  function claimAllCommon(address[] memory rewards) internal {
    for (uint16 i=0; i < rewards.length; i++)
      claim(rewards[i]);
  }

	/// @notice Allows the user to claim all their rewards in specified tokens.
	/// @param rewards An array of token addresses to claim rewards in.
	/// @param uncommonRewardIds An array of reward identifiers for uncommon rewards to claim.
  function claimAll(address[] memory rewards, uint256[] memory uncommonRewardIds) external nonReentrant {
    claimAllCommon(rewards);

    for (uint16 i=0; i < uncommonRewardIds.length; i++)
      claimUncommonReward(uncommonRewardIds[i]);
  }

	/// @notice Check if a user has initiated the unlock process.
	/// @param user The user to check the unlock status for.
	/// @return True if the user has initiated unlock, false otherwise.
  function unlockInitiated(address user) public view returns (bool) {
    return lockedUntil[user] > 0;
  }

	/// @notice Check if a user's stake is currently unlocked.
	/// @param user The user to check the lock status for.
	/// @return True if the user's stake is unlocked, false otherwise.
  function isUnlocked(address user) public view returns (bool) {
    return lockedUntil[user] < block.timestamp;
  }

	/// @notice Check the amount of RICE staked for a user
	/// @param user The user to check the lock status for.
	/// @return uint256 amount staked.
  function balanceOf(address user) public view returns (uint256) {
    return deposits[user];
  }

	/// @notice Internal function to add a new common reward token.
	/// @param token The token to add as a common reward.
	function ensureRewardToken(address token) internal {
		if (!isCommonReward[token]) {
			commonRewardTokens.push(token);
			isCommonReward[token] = true;
		}
	}

	/// @notice Get the exchange rate of ETH per token from the oracle.
	/// @param token The token to get the exchange rate for.
	/// @return The amount of ETH per token.
  function ethPerToken(address token) public view returns (uint256) {
    try oracle.ethPerToken(token) returns (uint256 result) {
      return result;
    } catch {
      return 0;
    }
  }

}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts/interfaces/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/extensions/IERC20Metadata.sol";

@openzeppelin/contracts/security/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

@openzeppelin/contracts/token/ERC20/ERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol

pragma solidity >=0.6.2;

interface IUniswapV2Router01 {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB, uint liquidity);
    function addLiquidityETH(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETH(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountToken, uint amountETH);
    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETHWithPermit(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountToken, uint amountETH);
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);
    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);

    function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
    function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}

@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol

pragma solidity >=0.6.2;

import './IUniswapV2Router01.sol';

interface IUniswapV2Router02 is IUniswapV2Router01 {
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountETH);
    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
}

project:/contracts/Oracle.sol

// contracts/Oracle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';

interface IV2Factory {
  function getPair(address tokenA, address tokenB) external view returns (address pair);
}

interface IUniswapV3Factory {
  function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool);
}

interface IUniswapV3Pool {
  function slot0() external view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked);
  function liquidity() external view returns (uint128);
}

contract Oracle {

  address public WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
  uint256 public constant PRECISION = 10**18;

  function v3EthPerToken(address token) public view returns (uint256) {
    IUniswapV3Factory factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984);

    uint16[3] memory feeTiers = [500, 3000, 10000];
    for (uint i = 0; i < feeTiers.length; i++) {
      IUniswapV3Pool poolV3 = IUniswapV3Pool(factory.getPool(token, WETH, feeTiers[i]));
      if (address(poolV3) != address(0)) {
        // uint128 liquidity = poolV3.liquidity();
        if (IERC20(WETH).balanceOf(address(poolV3)) > 2 ether) { // Check for sufficient liquidity
          (uint160 sqrtPriceX96,,,,,,) = poolV3.slot0();
          // Calculate price per token, adjust for sufficient liquidity
          uint pricePerToken = (((uint(sqrtPriceX96) * 10**9) / (2 ** 96)) ** 2);
          return pricePerToken;
        }
      }
    }
    return 0;
  }

  function v2EthPerToken(address token) public view returns (uint256) {
    IV2Factory uniswapV2Factory = IV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
    address pairV2 = uniswapV2Factory.getPair(token, WETH);

    IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);

    uint256 amountIn = 0.1 ether;
    address[] memory path = new address[](2);
    path[0] = WETH;
    path[1] = token;

    uint256[] memory amountsOut = uniswapV2Router.getAmountsOut(amountIn, path);

    // If there is less than 2 eth in the reserve, then
    // assume there is not enough liquidity to detmine a price
    if (IERC20(WETH).balanceOf(pairV2) > 2 ether)
      return (PRECISION * PRECISION / (10 * amountsOut[1]));

    return 0;
  }

  function ethPerToken(address token) public view returns (uint) {
    if (token == address(0)) return 1 ether;

    // Check Uniswap V2
    uint256 price = v2EthPerToken(token);
    if (price > 0) return price;

    // Uniswap V3 fee tiers
    return v3EthPerToken(token);
  }
}

project:/contracts/libraries/ERC20Helpers.sol

// SPDX-License-Identifier: GPL-3.0-or-later
import "@openzeppelin/contracts/interfaces/IERC20Metadata.sol";

pragma solidity >=0.6.0;

// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library ERC20Helpers {
  function safeApprove(
    address token,
    address to,
    uint256 value
  ) internal {
    // bytes4(keccak256(bytes('approve(address,uint256)')));
    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
    require(
      success && (data.length == 0 || abi.decode(data, (bool))),
      'ERC20Helpers::safeApprove: approve failed'
    );
  }

  function safeTransfer(
    address token,
    address to,
    uint256 value
  ) internal {
    // bytes4(keccak256(bytes('transfer(address,uint256)')));
    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
    require(
      success && (data.length == 0 || abi.decode(data, (bool))),
      'ERC20Helpers::safeTransfer: transfer failed'
    );
  }

  function safeTransferFrom(
    address token,
    address from,
    address to,
    uint256 value
  ) internal {
    // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
    require(
      success && (data.length == 0 || abi.decode(data, (bool))),
      'ERC20Helpers::transferFrom: transferFrom failed'
    );
  }

  function safeTransferETH(address to, uint256 value) internal {
    (bool success, ) = to.call{value: value}(new bytes(0));
    require(success, 'ERC20Helpers::safeTransferETH: ETH transfer failed');
  }

  /**
  * @dev Tries to fetch the decimals of the given token, defaults to 0 if undefined.
  * @param token The token contract to retrieve decimals from.
  * @return The number of decimals of the token.
  */
  function tryDecimals(IERC20Metadata token) internal view returns (uint8) {
    try token.decimals{gas: 20000}() returns (uint8 value) {
      return value;
    } catch {
      return 18; // Default value
    }
  }

  /**
  * @dev Tries to fetch the symbol of the given token, defaults to "UNKNOWN" if undefined.
  * @param token The token contract to retrieve the symbol from.
  * @return The symbol of the token.
  */
  function trySymbol(IERC20Metadata token) internal view returns (string memory) {
    try token.symbol{gas: 20000}() returns (string memory value) {
      return value;
    } catch {
      return "UNKNOWN"; // Default value
    }
  }

  /**
  * @dev Tries to fetch the name of the given token, defaults to "Unknown Token" if undefined.
  * @param token The token contract to retrieve the name from.
  * @return The name of the token.
  */
  function tryName(IERC20Metadata token) internal view returns (string memory) {
    try token.name{gas: 20000}() returns (string memory value) {
      return value;
    } catch {
      return "Unknown Token"; // Default value
    }
  }

}


Настройки компилятораПоказать
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": false
  },
  "evmVersion": "london",
  "remappings": []
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.