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

ReferralProgram

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

0 ETH

 

Транзакций

2

 

Компилятор

solc 0.8.38

 

Тот же код

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

 

Подробности

Компилятор
solc 0.8.38+commit.1835d247
Язык
solidity
Оптимизация
Да, 200 прогонов
Лицензия
MIT
Совпадение
Частичноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 491 885
Транзакция создания
0x7576cb3674…36b347fa6a

project/contracts/ReferralProgram.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.38;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {IDexTreasury} from "./interfaces/IDexTreasury.sol";
import {IReferralProgram} from "./interfaces/IReferralProgram.sol";
import {ITokenSource} from "./interfaces/ITokenSource.sol";

/**
 * @dev See {IReferralProgram}. Rates, the whitelist and the window are fixed at deployment (F-2);
 * only the mode changes, by the council (F-1).
 */
contract ReferralProgram is Ownable, IReferralProgram {
    using SafeERC20 for IERC20;

    uint256 public constant HUNDRED_PERCENT = 10_000;
    uint256 public constant REFERRAL_RATE = 1_000;
    uint256 public constant WHITELIST_REFERRAL_RATE = 5_000;

    uint256 public immutable referralWindow;

    IERC20 private _token;
    address private _stakeManager;

    ReferralMode public mode;
    uint256 public totalPaid;

    mapping(address referrer => bool) private _whitelisted;

    constructor(ReferralMode initialMode, uint256 window, address[] memory whitelist) Ownable(_msgSender()) {
        referralWindow = window;
        mode = initialMode;
        emit ReferralModeChanged(ReferralMode.Off, initialMode);

        for (uint256 i = 0; i < whitelist.length; ++i) {
            require(whitelist[i] != address(0), ZeroAddress());
            _whitelisted[whitelist[i]] = true;
            emit Whitelisted(whitelist[i]);
        }
    }

    function onStake(address owner, address referrer, uint256 amount, uint256 firstStakeAt) external {
        require(_msgSender() == _stakeManager, NotStakeManager(_msgSender()));

        if (referrer == address(0) || referrer == owner || referrer == _stakeManager || referrer == address(this)) {
            return;
        }

        uint256 rate = rateOf(referrer);
        if (rate == 0) {
            return;
        }

        if (firstStakeAt < block.timestamp && block.timestamp - firstStakeAt > referralWindow) {
            return;
        }

        uint256 bonus = (amount * rate) / HUNDRED_PERCENT;
        uint256 balance = _token.balanceOf(address(this));
        if (bonus > balance) {
            bonus = balance;
        }
        if (bonus == 0) {
            return;
        }

        totalPaid += bonus;
        _token.safeTransfer(referrer, bonus);

        emit ReferralPaid(referrer, owner, bonus);
    }

    function setStakeManager(address stakeManager_) external onlyOwner {
        require(_stakeManager == address(0), StakeManagerAlreadySet(_stakeManager));
        require(stakeManager_.code.length != 0, AddressWithoutCode(stakeManager_));

        IERC20 token_ = ITokenSource(stakeManager_).token();
        require(address(token_) != address(0), ZeroAddress());

        _stakeManager = stakeManager_;
        _token = token_;
        _transferOwnership(address(0));
    }

    function setMode(ReferralMode newMode) external {
        require(_stakeManager != address(0), StakeManagerNotSet());
        address caller = _msgSender();
        require(caller == IDexTreasury(_stakeManager).council(), NotCouncil(caller));

        ReferralMode previous = mode;
        require(newMode != previous, SameReferralMode(newMode));
        mode = newMode;

        emit ReferralModeChanged(previous, newMode);
    }

    function isWhitelisted(address referrer) external view returns (bool) {
        return _whitelisted[referrer];
    }

    function stakeManager() external view returns (address) {
        return _stakeManager;
    }

    function token() external view returns (IERC20) {
        return _token;
    }

    function available() external view returns (uint256) {
        return address(_token) == address(0) ? 0 : _token.balanceOf(address(this));
    }

    function rateOf(address referrer) public view returns (uint256) {
        ReferralMode current = mode;
        if (current == ReferralMode.Off) {
            return 0;
        }
        if (_whitelisted[referrer]) {
            return WHITELIST_REFERRAL_RATE;
        }
        return current == ReferralMode.On ? REFERRAL_RATE : 0;
    }

    function bonusFor(address referrer, uint256 amount) external view returns (uint256) {
        return (amount * rateOf(referrer)) / HUNDRED_PERCENT;
    }
}

npm/@openzeppelin/[email protected]/access/Ownable.sol

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

pragma solidity ^0.8.20;

import {Context} from "../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.
 *
 * The initial owner is set to the address provided by the deployer. 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;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @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 {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @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 {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _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);
    }
}

npm/@openzeppelin/[email protected]/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

npm/@openzeppelin/[email protected]/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

npm/@openzeppelin/[email protected]/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

npm/@openzeppelin/[email protected]/interfaces/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol

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

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}

npm/@openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
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);
}

npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /// @dev Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
    function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
        bytes4 selector = IERC20Metadata.decimals.selector;
        assembly ("memory-safe") {
            mstore(0x00, selector)
            success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
            success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
            decimals := mul(success, mload(0x00))
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, 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 to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
     * @param value The amount of token to approve
     * @param bubble Behavior switch if the approve call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

npm/@openzeppelin/[email protected]/utils/Context.sol

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

pragma solidity ^0.8.20;

/**
 * @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;
    }
}

npm/@openzeppelin/[email protected]/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

project/contracts/interfaces/IDexTreasury.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.38;

import {Dex, Venue, MintParams, IncreaseParams, DecreaseParams} from "../types/Dex.sol";

/**
 * @dev Governance-facing DEX side of a treasury: liquidity operations on Uniswap v3 compatible
 * venues, callable by the {council} only. Only allowed tokens are spent or bought, and the base
 * token sold through DEXes, net of what came back, never exceeds {dexSellCap}. The sold amount is
 * the treasury's own base balance change across each operation, not what the venue reports.
 * Positions and tokens never leave the treasury.
 */
interface IDexTreasury {
    event PositionMinted(
        Dex indexed dex,
        uint256 indexed tokenId,
        address token0,
        address token1,
        uint24 fee,
        int24 tickLower,
        int24 tickUpper
    );

    /**
     * @dev Emitted on mint too, right after {PositionMinted}.
     */
    event LiquidityIncreased(Dex indexed dex, uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);

    event LiquidityDecreased(
        Dex indexed dex,
        uint256 indexed tokenId,
        uint128 liquidity,
        uint256 amount0,
        uint256 amount1,
        uint256 fees0,
        uint256 fees1,
        bool burned
    );

    event FeesCollected(Dex indexed dex, uint256 indexed tokenId, uint256 amount0, uint256 amount1);

    /**
     * @dev Emitted whenever {dexSold}, and with it {dexSellLeft}, changes; also on deployment, with
     * nothing sold yet.
     */
    event DexSellLeftChanged(uint256 sold, uint256 left);

    error NotCouncil(address caller);
    error NoCouncil();
    error NoCode(address target);
    error ZeroDexAddress();
    error TokenNotAllowed(address token);
    error DexSellCapExceeded(uint256 sold, uint256 cap);
    error ZeroDexAmount();
    error UnsortedTokens(address token0, address token1);
    error PoolNotFound(address token0, address token1, uint24 fee);
    error ForeignPosition(uint256 tokenId, address owner);
    error InsufficientLiquidity(uint256 tokenId, uint128 available, uint128 requested);

    /**
     * @dev Opens a position on `dex`.
     */
    function mintPosition(
        Dex dex,
        MintParams calldata params
    ) external returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);

    /**
     * @dev Adds liquidity to a position the treasury owns.
     */
    function increaseLiquidity(
        Dex dex,
        IncreaseParams calldata params
    ) external returns (uint128 liquidity, uint256 amount0, uint256 amount1);

    /**
     * @dev Removes liquidity, collects everything owed (principal and fees) and burns the position
     * once it is empty.
     */
    function decreaseLiquidity(
        Dex dex,
        DecreaseParams calldata params
    ) external returns (uint256 amount0, uint256 amount1, uint256 fees0, uint256 fees1);

    /**
     * @dev Collects the fees accrued by position `tokenId`.
     */
    function collectFees(Dex dex, uint256 tokenId) external returns (uint256 amount0, uint256 amount1);

    /**
     * @dev Returns the only account allowed to run treasury operations.
     */
    function council() external view returns (address);

    /**
     * @dev Returns the contracts of `dex`.
     */
    function venue(Dex dex) external view returns (Venue memory);

    /**
     * @dev Returns the pair of position `tokenId` on `dex`.
     */
    function tokensOf(Dex dex, uint256 tokenId) external view returns (address token0, address token1);

    function isAllowedToken(address token) external view returns (bool);

    function dexSellCap() external view returns (uint256);

    function dexSold() external view returns (uint256);

    function dexSellLeft() external view returns (uint256);
}

project/contracts/interfaces/IReferralProgram.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.38;

import {IStakeHook} from "./IStakeHook.sol";
import {ITokenSource} from "./ITokenSource.sol";

/**
 * @dev Stake hook paying referrers a share of each referred stake from its own {ITokenSource-token}
 * balance, while the staker is within {referralWindow} of their first stake. Who is paid is set by
 * the {ReferralMode}, switched by the council of the stake manager; whitelisted referrers earn more.
 */
interface IReferralProgram is IStakeHook, ITokenSource {
    /**
     * @dev `Off` pays nobody, `WhitelistOnly` pays whitelisted referrers only, `On` pays everyone.
     */
    enum ReferralMode {
        Off,
        WhitelistOnly,
        On
    }

    event ReferralPaid(address indexed referrer, address indexed owner, uint256 amount);
    /// Also emitted on deployment, from `Off` to the initial mode.
    event ReferralModeChanged(ReferralMode oldMode, ReferralMode newMode);
    /// Emitted on deployment for each whitelisted referrer; the whitelist never changes after.
    event Whitelisted(address indexed referrer);

    error ZeroAddress();
    error NotStakeManager(address caller);
    error NotCouncil(address caller);
    error StakeManagerAlreadySet(address stakeManager);
    error StakeManagerNotSet();
    error AddressWithoutCode(address address_);
    error SameReferralMode(ReferralMode mode);

    /**
     * @dev Wires the stake manager once, adopts its token and renounces ownership.
     */
    function setStakeManager(address stakeManager_) external;

    /**
     * @dev Switches the mode. Council of the stake manager only.
     */
    function setMode(ReferralMode newMode) external;

    function mode() external view returns (ReferralMode);

    function referralWindow() external view returns (uint256);

    function isWhitelisted(address referrer) external view returns (bool);

    function totalPaid() external view returns (uint256);

    function stakeManager() external view returns (address);

    /**
     * @dev Returns the balance left to pay referrals from.
     */
    function available() external view returns (uint256);

    /**
     * @dev Returns the share of a referred stake paid to `referrer` under the current mode, in basis points.
     */
    function rateOf(address referrer) external view returns (uint256);

    /**
     * @dev Returns the bonus `referrer` would earn on a referred stake of `amount`, before the balance cap.
     */
    function bonusFor(address referrer, uint256 amount) external view returns (uint256);
}

project/contracts/interfaces/IStakeHook.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.38;

/**
 * @dev Receiver of staking notifications from a {StakeManager}.
 */
interface IStakeHook {
    /**
     * @dev Called by the stake manager after each deposit is recorded. A revert here reverts
     * the deposit, so implementations must decline quietly instead of reverting.
     * `firstStakeAt` is the depositor's first-ever deposit time.
     */
    function onStake(address owner, address referrer, uint256 amount, uint256 firstStakeAt) external;
}

project/contracts/interfaces/ITokenSource.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.38;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/**
 * @dev A contract whose accounting is denominated in a single primary ERC20 token.
 */
interface ITokenSource {
    /**
     * @dev Returns the primary token this contract operates on.
     */
    function token() external view returns (IERC20);
}

project/contracts/interfaces/external/uniswap-v3/INonfungiblePositionManager.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.38;

/**
 * @dev Uniswap v3 position manager; the PancakeSwap v3 one is ABI-identical.
 */
interface INonfungiblePositionManager {
    /**
     * @dev Parameters of {mint}. `token0`, `token1` and `fee` identify the pool;
     * `tickLower`/`tickUpper` set the range; the `Desired` amounts are offered and the `Min`
     * amounts are the least the call may consume; `recipient` gets the NFT.
     */
    struct MintParams {
        address token0;
        address token1;
        uint24 fee;
        int24 tickLower;
        int24 tickUpper;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        address recipient;
        uint256 deadline;
    }

    /**
     * @dev Parameters of {increaseLiquidity}: the position, the amounts offered and the least
     * amounts the call may consume.
     */
    struct IncreaseLiquidityParams {
        uint256 tokenId;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /**
     * @dev Parameters of {decreaseLiquidity}: the position, the liquidity to remove and the
     * least principal it must release.
     */
    struct DecreaseLiquidityParams {
        uint256 tokenId;
        uint128 liquidity;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /**
     * @dev Parameters of {collect}: the position, the receiver and caps on how much of what
     * is owed to take.
     */
    struct CollectParams {
        uint256 tokenId;
        address recipient;
        uint128 amount0Max;
        uint128 amount1Max;
    }

    /**
     * @dev Creates a position and mints its NFT to `recipient`; returns the token id, the
     * liquidity and the amounts actually consumed.
     */
    function mint(
        MintParams calldata params
    ) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);

    /**
     * @dev Adds liquidity to an existing position. Checks no ownership: anyone paying the tokens
     * tops up whosever NFT it is — callers guard the owner themselves.
     */
    function increaseLiquidity(
        IncreaseLiquidityParams calldata params
    ) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1);

    /**
     * @dev Removes liquidity and returns the principal released; transfers nothing — the amounts
     * become owed to the position and are paid by {collect}.
     */
    function decreaseLiquidity(
        DecreaseLiquidityParams calldata params
    ) external payable returns (uint256 amount0, uint256 amount1);

    /**
     * @dev Transfers what the position is owed — released principal plus accrued fees — and
     * returns what was actually paid.
     */
    function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);

    /**
     * @dev Burns the NFT of a position holding no liquidity and nothing owed.
     */
    function burn(uint256 tokenId) external payable;

    /**
     * @dev Returns the owner of position `tokenId` (plain ERC721).
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Returns the full book of position `tokenId`: the pool, the range, the liquidity and
     * what it is owed.
     */
    function positions(
        uint256 tokenId
    )
        external
        view
        returns (
            uint96 nonce,
            address operator,
            address token0,
            address token1,
            uint24 fee,
            int24 tickLower,
            int24 tickUpper,
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );
}

project/contracts/interfaces/external/uniswap-v3/IUniswapV3Factory.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.38;

/**
 * @dev Uniswap v3 factory; PancakeSwap v3 `PancakeV3Factory` exposes the same call.
 */
interface IUniswapV3Factory {
    /**
     * @dev Returns the pool for a pair and fee tier, zero when none exists; token order is free.
     */
    function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool);
}

project/contracts/types/Dex.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.38;

import {IUniswapV3Factory} from "../interfaces/external/uniswap-v3/IUniswapV3Factory.sol";
import {INonfungiblePositionManager} from "../interfaces/external/uniswap-v3/INonfungiblePositionManager.sol";

/**
 * @dev Uniswap v3 compatible deployments the treasury provides liquidity on.
 */
enum Dex {
    Uniswap,
    Pancake
}

/**
 * @dev The contracts of one Uniswap v3 compatible deployment.
 */
struct Venue {
    IUniswapV3Factory factory;
    INonfungiblePositionManager positionManager;
}

/**
 * @dev Parameters of a new position. `token0 < token1`; `fee` picks the pool; the range is
 * `[tickLower, tickUpper)`; `Desired` amounts are offered, `Min` amounts are the slippage floor.
 */
struct MintParams {
    address token0;
    address token1;
    uint24 fee;
    int24 tickLower;
    int24 tickUpper;
    uint256 amount0Desired;
    uint256 amount1Desired;
    uint256 amount0Min;
    uint256 amount1Min;
}

/**
 * @dev Parameters of adding liquidity: the position, the amounts offered and the slippage floor.
 */
struct IncreaseParams {
    uint256 tokenId;
    uint256 amount0Desired;
    uint256 amount1Desired;
    uint256 amount0Min;
    uint256 amount1Min;
}

/**
 * @dev Parameters of removing liquidity: the position, the liquidity to remove and the least
 * principal it must release.
 */
struct DecreaseParams {
    uint256 tokenId;
    uint128 liquidity;
    uint256 amount0Min;
    uint256 amount1Min;
}

/**
 * @dev Outcome of adding liquidity: the pair, the liquidity added and the amounts consumed.
 */
struct IncreaseResult {
    uint256 tokenId;
    address token0;
    address token1;
    uint128 liquidity;
    uint256 amount0;
    uint256 amount1;
}

/**
 * @dev Outcome of removing liquidity: the pair, the principal released, the fees collected
 * alongside it and whether the emptied position was burned.
 */
struct DecreaseResult {
    uint256 tokenId;
    address token0;
    address token1;
    uint256 amount0;
    uint256 amount1;
    uint256 fees0;
    uint256 fees1;
    bool burned;
}
Настройки компилятораПоказать
{
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": [
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/"
  ]
}

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

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