Skip to content
Verified contractExactMIT

BackedAutoFeeTokenImplementation

Address0x65c40d624af3b18c109fbf87b7deff34cdc5f19b
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.9

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.9+commit.e5eed63a
Language
solidity
Optimization
Yes, 10 runs
EVM version
london
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,388,185
Creation transaction
0x0e011787ea…2099886d80

contracts/BackedAutoFeeTokenImplementation.sol

/**
 * SPDX-License-Identifier: MIT
 *
 * Copyright (c) 2021-2024 Backed Finance AG
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/**
 * Disclaimer and Terms of Use
 *
 * These ERC-20 tokens have not been registered under the U.S. Securities Act of 1933, as
 * amended or with any securities regulatory authority of any State or other jurisdiction
 * of the United States and (i) may not be offered, sold or delivered within the United States
 * to, or for the account or benefit of U.S. Persons, and (ii) may be offered, sold or otherwise
 * delivered at any time only to transferees that are Non-United States Persons (as defined by
 * the U.S. Commodities Futures Trading Commission).
 * For more information and restrictions please refer to the issuer's [Website](https://www.backedassets.fi/legal-documentation)
 */

pragma solidity 0.8.9;

import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./BackedTokenImplementation.sol";
import "./interfaces/IBackedAutoFeeToken.sol";

/**
 * @dev
 *
 * This token contract is following the ERC20 standard.
 * It inherits BackedTokenImplementation.sol, which is base Backed token implementation. BackedAutoFeeTokenImplementation extends it
 * with logic of multiplier, which is used for rebasing logic of the token, thus becoming rebase token itself. Additionally, it contains
 * mechanism, which changes this multiplier per configured fee periodically, on defined period length.
 * It contains one additional role:
 *  - A multiplierUpdater, that can update value of a multiplier.
 *
 */

contract BackedAutoFeeTokenImplementation is BackedTokenImplementation, IBackedAutoFeeToken {
    // Calculating the Delegated Transfer Shares typehash:
    bytes32 constant public DELEGATED_TRANSFER_SHARES_TYPEHASH =
        keccak256(
            "DELEGATED_TRANSFER_SHARES(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)"
        );

    // Roles:
    address public multiplierUpdater;

    // Management Fee
    uint256 public lastTimeFeeApplied;
    uint256 public feePerPeriod; // in 1e18 precision
    uint256 public periodLength;

    /**
     * @dev Defines ratio between a single share of a token to balance of a token.
     * Defined in 1e18 precision.
     *
     */
    uint256 public lastMultiplier;
    function multiplier() external view returns (uint256) {
        if(block.timestamp >= newMultiplierActivationTime) {
            return newMultiplier;
        }
        return lastMultiplier;
    }

    mapping(address => uint256) private _shares;

    uint256 internal _totalShares;

    uint256 public lastMultiplierNonce;
    uint256 public newMultiplierNonce;
    uint256 public newMultiplier;
    uint256 public newMultiplierActivationTime;

    /**
     * @dev Append-only log of *explicit* multiplier updates submitted via
     * `updateMultiplierValue` / `updateMultiplierWithNonce`.
     *
     * Index 0 is a genesis sentinel `{1e18, 1e18, 0}` so that
     * `_storeScheduledMultiplierUpdate` can safely read `length - 1`.
     *
     * Pending future-dated entries are overridden in place: when a new
     * explicit update is submitted while the previous one is still
     * scheduled (activationTime > block.timestamp), the previous entry is
     * popped before the new one is appended. The corresponding
     * `MultiplierScheduled` event from the popped entry remains on chain;
     * the array does not retain it.
     */
    MultiplierUpdate[] public multiplierUpdates;

    function multiplierNonce() external view returns (uint256) {
        if(block.timestamp >= newMultiplierActivationTime) {
            return newMultiplierNonce;
        }
        return lastMultiplierNonce;
    }

    // Modifiers:

    modifier updateMultiplier() {
        (uint256 currentMultiplier, uint256 periodsPassed, uint256 currentMultiplierNonce) = getCurrentMultiplier();
        lastTimeFeeApplied = lastTimeFeeApplied + periodLength * periodsPassed;
        if (lastMultiplier != currentMultiplier) {
            _updateMultiplier(currentMultiplier, currentMultiplierNonce, 0);
        }
        _;
    }

    modifier onlyMultiplierUpdater() {
        require(
            _msgSender() == multiplierUpdater,
            "BackedToken: Only multiplier updater"
        );
        _;
    }

    modifier onlyUpdatedMultiplier(uint256 oldMultiplier) {
        (uint256 currentMultiplier,,) = getCurrentMultiplier();
        require(
            currentMultiplier == oldMultiplier,
            "BackedToken: Multiplier changed in the meantime"
        );
        _;
    }

    modifier onlyNewerMultiplierNonce(uint256 newMultiplierNonce) {
        (,,uint256 currentMultiplierNonce) = getCurrentMultiplier();
        require(
            currentMultiplierNonce < newMultiplierNonce,
            "BackedToken: Multiplier nonce is outdated."
        );
        _;
    }
    
    // constructor, set lastTimeFeeApplied to lock the implementation instance.
    constructor () {
        lastTimeFeeApplied = 1;
    }

    // Initializers:
    function initialize(
        string memory name_,
        string memory symbol_
    ) public virtual override(BackedTokenImplementation, IBackedToken) {
        super.initialize(name_, symbol_);
        _initialize_auto_fee(24 * 3600, block.timestamp, 0);
    }

    function initialize(
        string memory name_,
        string memory symbol_,
        uint256 _periodLength,
        uint256 _lastTimeFeeApplied,
        uint256 _feePerPeriod
    ) external virtual {
        super.initialize(name_, symbol_);
        _initialize_auto_fee(_periodLength, _lastTimeFeeApplied, _feePerPeriod);
    }

    // Should it be only callable by authorized address?
    function initialize_v2(
        uint256 _periodLength,
        uint256 _lastTimeFeeApplied,
        uint256 _feePerPeriod
    ) external virtual {
        _initialize_auto_fee(_periodLength, _lastTimeFeeApplied, _feePerPeriod);
    }

    function initialize_v3(
    ) external virtual {
        require(newMultiplier == 0, "BackedAutoFeeTokenImplementation v3 already initialized");
        newMultiplier = lastMultiplier;
        newMultiplierNonce = lastMultiplierNonce;
        newMultiplierActivationTime = 0;
    }

    function initialize_v4(
        MultiplierUpdate [] calldata _pastMultipliersUpdates
    ) external virtual {
        require(multiplierUpdates.length == 0, "BackedAutoFeeTokenImplementation v4 already initialized");
        multiplierUpdates.push(MultiplierUpdate({
            previousMultiplier: 1e18,
            newMultiplier: 1e18,
            activationTime: 0
        }));
        for (uint i = 0; i < _pastMultipliersUpdates.length; i++) {
            require(_pastMultipliersUpdates[i].previousMultiplier > 0, "BackedAutoFeeTokenImplementation: previousMultiplier cannot be zero");
            multiplierUpdates.push(MultiplierUpdate({
                previousMultiplier: _pastMultipliersUpdates[i].previousMultiplier,
                newMultiplier: _pastMultipliersUpdates[i].newMultiplier,
                activationTime: _pastMultipliersUpdates[i].activationTime
            }));
        }
    }

    function _initialize_auto_fee(
        uint256 _periodLength,
        uint256 _lastTimeFeeApplied,
        uint256 _feePerPeriod
    ) internal virtual {
        require(lastTimeFeeApplied == 0, "BackedAutoFeeTokenImplementation already initialized");
        require(_lastTimeFeeApplied != 0, "Invalid last time fee applied");

        lastMultiplier = 1e18;
        lastMultiplierNonce = 0;
        newMultiplier = 1e18;
        newMultiplierNonce = 0;
        newMultiplierActivationTime = 0;
        periodLength = _periodLength;
        lastTimeFeeApplied = _lastTimeFeeApplied;
        feePerPeriod = _feePerPeriod;
        multiplierUpdates.push(MultiplierUpdate({
            previousMultiplier: 1e18,
            newMultiplier: 1e18,
            activationTime: 0
        }));
    }

    /**
     * @inheritdoc IERC20MetadataUpgradeable
     */
    function decimals() public view virtual override(BackedTokenImplementation, IBackedToken) returns (uint8) {
        return ERC20Upgradeable.decimals();
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        (uint256 currentMultiplier, ,) = getCurrentMultiplier();
        return _getUnderlyingAmountByShares(_totalShares, currentMultiplier);
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(
        address account
    ) public view virtual override returns (uint256) {
        (uint256 currentMultiplier, ,) = getCurrentMultiplier();
        return _getUnderlyingAmountByShares(sharesOf(account), currentMultiplier);
    }

    /**
     * @dev Retrieves most up to date value of multiplier
     *
     */
    function getCurrentMultiplier()
        public
        view
        virtual
        returns (uint256 currentMultiplier, uint256 periodsPassed, uint256 currentMultiplierNonce)
    {
        if(block.timestamp < newMultiplierActivationTime) {
            return (lastMultiplier, 0, lastMultiplierNonce);
        }
        periodsPassed = (block.timestamp - lastTimeFeeApplied) / periodLength;
        currentMultiplier = newMultiplier;
        currentMultiplierNonce = newMultiplierNonce;
        if (feePerPeriod > 0) {
            for (uint256 index = 0; index < periodsPassed; index++) {
                currentMultiplier = (currentMultiplier * (1e18 - feePerPeriod)) / 1e18;
            }
            currentMultiplierNonce += periodsPassed;
        }
    }

    /**
     * @dev Returns amount of shares owned by given account
     */
    function sharesOf(address account) public view virtual returns (uint256) {
        return _shares[account];
    }

    /**
     * @return the amount of shares that corresponds to `_underlyingAmount` underlying amount.
     */
    function getSharesByUnderlyingAmount(
        uint256 _underlyingAmount
    ) external view returns (uint256) {
        (uint256 currentMultiplier, ,) = getCurrentMultiplier();
        return _getSharesByUnderlyingAmount(_underlyingAmount, currentMultiplier);
    }

    /**
     * @return the amount of underlying that corresponds to `_sharesAmount` token shares.
     */
    function getUnderlyingAmountByShares(
        uint256 _sharesAmount
    ) external view returns (uint256) {
        (uint256 currentMultiplier, ,) = getCurrentMultiplier();
        return _getUnderlyingAmountByShares(_sharesAmount, currentMultiplier);
    }

    /**
     * @return Length of scheduled multipliers updates array
     */
    function multiplierUpdatesLength() external view returns (uint256) {
        return multiplierUpdates.length;
    }

    /**
     * @dev Delegated Transfer Shares, transfer shares via a sign message, using erc712.
     */
    function delegatedTransferShares(
        address owner,
        address to,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external virtual allowedDelegate updateMultiplier {
        require(block.timestamp <= deadline, "ERC20Permit: expired deadline");

        bytes32 structHash = keccak256(
            abi.encode(
                DELEGATED_TRANSFER_SHARES_TYPEHASH,
                owner,
                to,
                value,
                _useNonce(owner),
                deadline
            )
        );
        _checkOwner(owner, structHash, v, r, s);

        _transferShares(owner, to, value);
    }

    /**
     * @dev Transfers underlying shares to destination account
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `sharesAmount`.
     */
    function transferShares(
        address to,
        uint256 sharesAmount
    ) external virtual updateMultiplier returns (bool) {
        address owner = _msgSender();
        _transferShares(owner, to, sharesAmount);

        return true;
    }

    /**
     * @dev Transfers underlying shares from source account to destination account
     *
     * Requirements:
     *
     * - `from` cannot be the zero address and caller needs to have permission to use it's allowance.
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `sharesAmount`.
     */
    function transferSharesFrom(
        address from,
        address to,
        uint256 sharesAmount
    ) external virtual updateMultiplier returns (bool) {
        uint256 amount = _getUnderlyingAmountByShares(sharesAmount, lastMultiplier);
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transferShares(from, to, sharesAmount, amount);
        return true;
    }

    /**
     * @dev Function to set the new fee. Allowed only for owner
     *
     * @param newFeePerPeriod The new fee per period value
     */
    function updateFeePerPeriod(
        uint256 newFeePerPeriod
    ) external onlyOwner updateMultiplier {
        require(newMultiplierActivationTime == 0, "Multiplier activation in progress");
        feePerPeriod = newFeePerPeriod;
    }

    /**
     * @dev Function to change the contract multiplier updater. Allowed only for owner
     *
     * Emits a { NewMultiplierUpdater } event
     *
     * @param newMultiplierUpdater The address of the new multiplier updater
     */
    function setMultiplierUpdater(
        address newMultiplierUpdater
    ) external onlyOwner {
        multiplierUpdater = newMultiplierUpdater;
        emit NewMultiplierUpdater(newMultiplierUpdater);
    }

    /**
     * @dev Function to change the time of last fee accrual. Allowed only for owner
     *
     * @param newLastTimeFeeApplied A timestamp of last time fee was applied
     */
    function setLastTimeFeeApplied(
        uint256 newLastTimeFeeApplied
    ) external onlyOwner updateMultiplier {
        require(newMultiplierActivationTime == 0, "Multiplier activation in progress");
        require(newLastTimeFeeApplied != 0, "Invalid last time fee applied");
        lastTimeFeeApplied = newLastTimeFeeApplied;
    }

    /**
     * @dev Function to change period length. Allowed only for owner
     *
     * @param newPeriodLength Length of a single accrual period in seconds
     */
    function setPeriodLength(uint256 newPeriodLength) external onlyOwner updateMultiplier {
        require(newMultiplierActivationTime == 0, "Multiplier activation in progress");
        periodLength = newPeriodLength;
    }

    /**
     * @dev Function to change the contract multiplier, only if oldMultiplier did not change in the meantime. Allowed only for multiplierUpdater
     *
     * Emits a { MultiplierChanged } event
     *
     * @param pendingNewMultiplier New multiplier value
     * @param oldMultiplier Old multiplier value
     * @param pendingNewMultiplierActivationTime Time when new multiplier becomes active, which needs to take place before start of the next period
     */
    function updateMultiplierValue(
        uint256 pendingNewMultiplier,
        uint256 oldMultiplier,
        uint256 pendingNewMultiplierActivationTime
    ) public onlyMultiplierUpdater updateMultiplier onlyUpdatedMultiplier(oldMultiplier) {
        _updateMultiplier(pendingNewMultiplier, lastMultiplierNonce + 1, pendingNewMultiplierActivationTime);
        _storeScheduledMultiplierUpdate(oldMultiplier, pendingNewMultiplier, pendingNewMultiplierActivationTime);
    }

    /**
     * @dev Function to change the contract multiplier with nonce, only if oldMultiplier did not change in the meantime. Allowed only for multiplierUpdater
     *
     * Emits a { MultiplierChanged } event
     *
     * @param newMultiplier New multiplier value
     * @param newMultiplierNonce New multplier nonce
     */
    function updateMultiplierWithNonce(
        uint256 newMultiplier,
        uint256 oldMultiplier,
        uint256 newMultiplierNonce,
        uint256 pendingNewMultiplierActivationTime
    ) external onlyMultiplierUpdater updateMultiplier onlyUpdatedMultiplier(oldMultiplier) onlyNewerMultiplierNonce(newMultiplierNonce){
        _updateMultiplier(newMultiplier, newMultiplierNonce, pendingNewMultiplierActivationTime);
        _storeScheduledMultiplierUpdate(oldMultiplier, newMultiplier, pendingNewMultiplierActivationTime);
    }

    /**
     * @dev Stores an explicit multiplier update in `multiplierUpdates`.
     *
     * If the previously stored entry is still pending (activationTime in the
     * future), it is overwritten in place — only one scheduled update can be
     * pending at a time — and a `MultiplierScheduleOverridden` event is
     * emitted so off-chain consumers can reconcile the now-stale
     * `MultiplierScheduled` event for the discarded entry.
     *
     * Tolerates an empty array (the not-yet-migrated state between a v4
     * implementation upgrade and an `initialize_v4` call) by falling through
     * to the append path.
     */
    function _storeScheduledMultiplierUpdate(
        uint256 _previousMultiplierValue,
        uint256 _multiplierValue,
        uint256 _multiplierActivationTime
    ) internal {
        MultiplierUpdate memory entry = MultiplierUpdate({
            previousMultiplier: _previousMultiplierValue,
            newMultiplier: _multiplierValue,
            activationTime: _multiplierActivationTime > block.timestamp ? _multiplierActivationTime : block.timestamp
        });

        uint256 len = multiplierUpdates.length;
        if (len > 0 && multiplierUpdates[len - 1].activationTime > block.timestamp) {
            MultiplierUpdate memory overridden = multiplierUpdates[len - 1];
            multiplierUpdates[len - 1] = entry;
            emit MultiplierScheduleOverridden(
                overridden.newMultiplier,
                overridden.activationTime,
                entry.newMultiplier,
                entry.activationTime
            );
        } else {
            multiplierUpdates.push(entry);
        }
    }

    /**
     * @return the amount of shares that corresponds to `_underlyingAmount` underlying amount.
     */
    function _getSharesByUnderlyingAmount(
        uint256 _underlyingAmount,
        uint256 _multiplier
    ) internal pure returns (uint256) {
        return (_underlyingAmount * 1e18) / _multiplier;
    }

    /**
     * @return the amount of underlying that corresponds to `_sharesAmount` token shares.
     */
    function _getUnderlyingAmountByShares(
        uint256 _sharesAmount,
        uint256 _multiplier
    ) internal pure returns (uint256) {
        return (_sharesAmount * _multiplier) / 1e18;
    }

    /**
     * @dev Moves `amount` of tokens from `sender` to `recipient`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     * 
     * 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 override {
        (uint256 multiplier, ,) = getCurrentMultiplier();
        uint256 _sharesAmount = _getSharesByUnderlyingAmount(
            amount,
            multiplier
        );
        _transferShares(from, to, _sharesAmount, amount);
    }

    /**
     * @dev Moves `shares amount` of tokens from `sender` to `recipient`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `sharesAmount`.
     */
    function _transferShares(
        address from,
        address to,
        uint256 sharesAmount
    ) internal virtual {
        (uint256 multiplier, ,) = getCurrentMultiplier();
         uint256 amount = _getUnderlyingAmountByShares(
            sharesAmount,
            multiplier
        );
        _transferShares(from, to, sharesAmount, amount);
    }
    
    /**
     * @dev Moves `shares amount` of tokens from `sender` to `recipient`.
     *
     * Emits a {Transfer} event.
     * Emits a {TransferShares} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `sharesAmount`.
     */
    function _transferShares(
        address from,
        address to,
        uint256 sharesAmount,
        uint256 tokenAmount
    ) 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, tokenAmount);

        uint256 currentSenderShares = _shares[from];
        require(
            currentSenderShares >= sharesAmount,
            "ERC20: transfer amount exceeds balance"
        );

        unchecked {
            _shares[from] = currentSenderShares - (sharesAmount);
        }
        _shares[to] = _shares[to] + (sharesAmount);

        emit Transfer(from, to, tokenAmount);
        emit TransferShares(from, to, sharesAmount);

        _afterTokenTransfer(from, to, tokenAmount);
    }

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

        _beforeTokenTransfer(address(0), account, amount);
        (uint256 multiplier, ,) = getCurrentMultiplier();
        uint256 sharesAmount = _getSharesByUnderlyingAmount(amount, multiplier);

        _totalShares += sharesAmount;
        _shares[account] += sharesAmount;
        emit Transfer(address(0), account, amount);
        emit TransferShares(address(0), account, sharesAmount);

        _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.
     * Emits a {TransferShares} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `sharesAmount` token shares.
     */
    function _burn(address account, uint256 amount) internal virtual override {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);
        (uint256 multiplier, ,) = getCurrentMultiplier();
        uint256 sharesAmount = _getSharesByUnderlyingAmount(amount, multiplier);

        uint256 accountBalance = _shares[account];
        require(
            accountBalance >= sharesAmount,
            "ERC20: burn amount exceeds balance"
        );
        unchecked {
            _shares[account] = accountBalance - sharesAmount;
        }
        _totalShares -= sharesAmount;

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

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

    /**
     * @dev Updates currently stored multiplier with a new value
     *
     * Emit an {MultiplierUpdated} event.
     */
    function _updateMultiplier(uint256 pendingNewMultiplier, uint256 pendingNewMultiplierNonce, uint256 pendingNewMultiplierActivationTime) internal virtual {
        require(pendingNewMultiplier != 0, "BackedToken: Multiplier cannot be zero");
        require(pendingNewMultiplierActivationTime < lastTimeFeeApplied + periodLength, "BackedToken: Activation time needs to be before next period");

        newMultiplier = pendingNewMultiplier;
        newMultiplierNonce = pendingNewMultiplierNonce;

        if(pendingNewMultiplierActivationTime > block.timestamp) {
            newMultiplierActivationTime = pendingNewMultiplierActivationTime;
            emit MultiplierScheduled(pendingNewMultiplier, pendingNewMultiplierActivationTime);
            // We don't need to update lastMultiplier and lastMultiplierNonce here, as they will be updated in updateMultiplier modifier when calling updateMultiplier method
        } else {
            newMultiplierActivationTime = 0;
            lastMultiplier = pendingNewMultiplier;
            lastMultiplierNonce = pendingNewMultiplierNonce;
            emit MultiplierUpdated(pendingNewMultiplier);
        }
    }

    // Implement the update multiplier functionality before transfer:
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual override updateMultiplier {
        super._beforeTokenTransfer(from, to, amount);
    }
}

@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol

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

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
    address private _owner;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    function __Ownable_init() internal onlyInitializing {
        __Ownable_init_unchained();
    }

    function __Ownable_init_unchained() internal onlyInitializing {
        _transferOwnership(_msgSender());
    }

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

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public 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);
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.0;

import "../../utils/AddressUpgradeable.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
 * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() initializer {}
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     */
    bool private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Modifier to protect an initializer function from being invoked twice.
     */
    modifier initializer() {
        // If the contract is initializing we ignore whether _initialized is set in order to support multiple
        // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
        // contract may have been reentered.
        require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");

        bool isTopLevelCall = !_initializing;
        if (isTopLevelCall) {
            _initializing = true;
            _initialized = true;
        }

        _;

        if (isTopLevelCall) {
            _initializing = false;
        }
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} modifier, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    function _isConstructor() private view returns (bool) {
        return !AddressUpgradeable.isContract(address(this));
    }
}

@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol

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

pragma solidity ^0.8.0;

import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
    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}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        _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 value {ERC20} uses, unless this function is
     * 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, _allowances[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 = _allowances[owner][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `sender` to `recipient`.
     *
     * 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;
        }
        _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;
        _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;
        }
        _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 Spend `amount` form the allowance of `owner` toward `spender`.
     *
     * 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 {}

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[45] private __gap;
}

@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20Upgradeable {
    /**
     * @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);

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

@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol

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

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
    /**
     * @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-upgradeable/utils/AddressUpgradeable.sol

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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol

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

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }
}

@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../StringsUpgradeable.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSAUpgradeable {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        } else if (error == RecoverError.InvalidSignatureV) {
            revert("ECDSA: invalid signature 'v' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        // Check the signature length
        // - case 65: r,s,v signature (standard)
        // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else if (signature.length == 64) {
            bytes32 r;
            bytes32 vs;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                vs := mload(add(signature, 0x40))
            }
            return tryRecover(hash, r, vs);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }
        if (v != 27 && v != 28) {
            return (address(0), RecoverError.InvalidSignatureV);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}

contracts/BackedTokenImplementation.sol

/**
 * SPDX-License-Identifier: MIT
 *
 * Copyright (c) 2021-2022 Backed Finance AG
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/**
 * Disclaimer and Terms of Use
 *
 * These ERC-20 tokens have not been registered under the U.S. Securities Act of 1933, as
 * amended or with any securities regulatory authority of any State or other jurisdiction
 * of the United States and (i) may not be offered, sold or delivered within the United States
 * to, or for the account or benefit of U.S. Persons, and (ii) may be offered, sold or otherwise
 * delivered at any time only to transferees that are Non-United States Persons (as defined by 
 * the U.S. Commodities Futures Trading Commission). 
 * For more information and restrictions please refer to the issuer's [Website](https://www.backedassets.fi/legal-documentation)
 */

pragma solidity 0.8.9;

import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./ERC20PermitDelegateTransfer.sol";
import "./SanctionsList.sol";
import "./interfaces/IBackedToken.sol";

/**
 * @dev
 *
 * This token contract is following the ERC20 standard.
 * It inherits ERC20PermitDelegateTransfer.sol, which extends the basic ERC20 to also allow permit and delegateTransfer EIP-712 functionality.
 * Enforces Sanctions List via the Chainalysis standard interface.
 * The contract contains three roles:
 *  - A minter, that can mint new tokens.
 *  - A burner, that can burn its own tokens, or contract's tokens.
 *  - A pauser, that can pause or restore all transfers in the contract.
 *  - An owner, that can set the three above, and also the sanctionsList pointer.
 * The owner can also set who can use the EIP-712 functionality, either specific accounts via a whitelist, or everyone.
 * 
 */

contract BackedTokenImplementation is OwnableUpgradeable, ERC20PermitDelegateTransfer, IBackedToken {
    string constant public VERSION = "1.1.0";

    // Roles:
    address public minter;
    address public burner;
    address public pauser;

    // EIP-712 Delegate Functionality:
    bool public delegateMode;
    mapping(address => bool) public delegateWhitelist;

    // Pause:
    bool public isPaused;

    // SanctionsList:
    SanctionsList public sanctionsList;

    // Terms:
    string public terms;

    modifier allowedDelegate {
        require(delegateMode || delegateWhitelist[_msgSender()], "BackedToken: Unauthorized delegate");
        _;
    }


    // constructor, call initializer to lock the implementation instance.
    constructor () {
        initialize("Backed Token Implementation", "BTI");
    }

    function initialize(string memory name_, string memory symbol_) public virtual initializer {
        __ERC20_init(name_, symbol_);
        __Ownable_init();
        _buildDomainSeparator();
        _setTerms("https://www.backedassets.fi/legal-documentation"); // Default Terms
    }

    /**
     * @dev Update allowance with a signed permit. Allowed only if
     *  the sender is whitelisted, or the delegateMode is set to true
     *
     * @param owner       Token owner's address (Authorizer)
     * @param spender     Spender's address
     * @param value       Amount of allowance
     * @param deadline    Expiration time, seconds since the epoch
     * @param v           v part of the signature
     * @param r           r part of the signature
     * @param s           s part of the signature
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public override allowedDelegate {
        super.permit(owner, spender, value, deadline, v, r, s);
    }

    /**
     * @dev Perform an intended transfer on one account's behalf, from another account,
     *  who actually pays fees for the transaction. Allowed only if the sender
     *  is whitelisted, or the delegateMode is set to true
     *
     * @param owner       The account that provided the signature and from which the tokens will be taken
     * @param to          The account that will receive the tokens
     * @param value       The amount of tokens to transfer
     * @param deadline    Expiration time, seconds since the epoch
     * @param v           v part of the signature
     * @param r           r part of the signature
     * @param s           s part of the signature
     */
    function delegatedTransfer(
        address owner,
        address to,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual override allowedDelegate {
        super.delegatedTransfer(owner, to, value, deadline, v, r, s);
    }

    function decimals() public view virtual override(ERC20Upgradeable, IBackedToken) returns (uint8) {
        return super.decimals();
    }

    /**
     * @dev Function to mint tokens. Allowed only for minter
     *
     * @param account   The address that will receive the minted tokens
     * @param amount    The amount of tokens to mint
     */
    function mint(address account, uint256 amount) virtual external {
        require(_msgSender() == minter, "BackedToken: Only minter");
        _mint(account, amount);
    }


    /**
     * @dev Function to burn tokens. Allowed only for burner. The burned tokens
     *  must be from the burner (msg.sender), or from the contract itself
     *
     * @param account   The account from which the tokens will be burned
     * @param amount    The amount of tokens to be burned
     */
    function burn(address account, uint256 amount) virtual external {
        require(_msgSender() == burner, "BackedToken: Only burner");
        require(account == _msgSender() || account == address(this), "BackedToken: Cannot burn account");
        _burn(account, amount);
    }


    /**
     * @dev Function to set the pause in order to block or restore all
     *  transfers. Allowed only for pauser
     *
     * Emits a { PauseModeChange } event
     *
     * @param newPauseMode The new pause mode
     */
    function setPause(bool newPauseMode) external {
        require(_msgSender() == pauser, "BackedToken: Only pauser");
        isPaused = newPauseMode;
        emit PauseModeChange(newPauseMode);
    }

    /**
     * @dev Function to change the contract minter. Allowed only for owner
     *
     * Emits a { NewMinter } event
     *
     * @param newMinter The address of the new minter
     */
    function setMinter(address newMinter) external onlyOwner {
        minter = newMinter;
        emit NewMinter(newMinter);
    }

    /**
     * @dev Function to change the contract burner. Allowed only for owner
     *
     * Emits a { NewBurner } event
     *
     * @param newBurner The address of the new burner
     */
    function setBurner(address newBurner) external onlyOwner {
        burner = newBurner;
        emit NewBurner(newBurner);
    }

    /**
     * @dev Function to change the contract pauser. Allowed only for owner
     *
     * Emits a { NewPauser } event
     *
     * @param newPauser The address of the new pauser
     */
    function setPauser(address newPauser) external onlyOwner {
        pauser = newPauser;
        emit NewPauser(newPauser);
    }

    /**
     * @dev Function to change the contract Senctions List. Allowed only for owner
     *
     * Emits a { NewSanctionsList } event
     *
     * @param newSanctionsList The address of the new Senctions List following the Chainalysis standard
     */
    function setSanctionsList(address newSanctionsList) external onlyOwner {
        // Check the proposed sanctions list contract has the right interface:
        require(!SanctionsList(newSanctionsList).isSanctioned(address(this)), "BackedToken: Wrong List interface");

        sanctionsList = SanctionsList(newSanctionsList);
        emit NewSanctionsList(newSanctionsList);
    }


    /**
     * @dev EIP-712 Function to change the delegate status of account.
     *  Allowed only for owner
     *
     * Emits a { DelegateWhitelistChange } event
     *
     * @param whitelistAddress  The address for which to change the delegate status
     * @param status            The new delegate status
     */
    function setDelegateWhitelist(address whitelistAddress, bool status) external onlyOwner {
        delegateWhitelist[whitelistAddress] = status;
        emit DelegateWhitelistChange(whitelistAddress, status);
    }

    /**
     * @dev EIP-712 Function to change the contract delegate mode. Allowed
     *  only for owner
     *
     * Emits a { DelegateModeChange } event
     *
     * @param _delegateMode The new delegate mode for the contract
     */
    function setDelegateMode(bool _delegateMode) external onlyOwner {
        delegateMode = _delegateMode;

        emit DelegateModeChange(_delegateMode);
    }

    /**
     * @dev Function to change the contract terms. Allowed only for owner
     *
     * Emits a { NewTerms } event
     *
     * @param newTerms A string with the terms. Usually a web or IPFS link.
     */
    function setTerms(string memory newTerms) external onlyOwner {
        _setTerms(newTerms);
    }

    // Implement setTerms, tp allow also to use from initializer:
    function _setTerms(string memory newTerms) internal virtual {
        terms = newTerms;
        emit NewTerms(newTerms);
    }

    // Implement the pause and SanctionsList functionality before transfer:
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual override {
        // Check not paused:
        require(!isPaused, "BackedToken: token transfer while paused");

        // Check Sanctions List, but do not prevent minting burning:
        if (from != address(0) && to != address(0)) {
            require(!sanctionsList.isSanctioned(from), "BackedToken: sender is sanctioned");
            require(!sanctionsList.isSanctioned(to), "BackedToken: receiver is sanctioned");
        }

        super._beforeTokenTransfer(from, to, amount);
    }

    // Implement the SanctionsList functionality for spender:
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual override {
        require(!sanctionsList.isSanctioned(spender), "BackedToken: spender is sanctioned");

        super._spendAllowance(owner, spender, amount);
    }
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

contracts/ERC20PermitDelegateTransfer.sol

/**
 * SPDX-License-Identifier: MIT
 *
 * Copyright (c) 2021-2022 Backed Finance AG
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
pragma solidity 0.8.9;

import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";

/**
 * @dev 
 *
 * This contract is a based (copy-paste with changes) on OpenZeppelin's draft-ERC20Permit.sol (token/ERC20/extensions/draft-ERC20Permit.sol).
 * 
 * The changes are:
 *  - Adding also delegated transfer functionality, that is similar to permit, but doing the actual transfer and not approval.
 *  - Cutting some of the generalities to make the contacts more straight forward for this case (e.g. removing the counters library). 
 *
*/

contract ERC20PermitDelegateTransfer is ERC20Upgradeable {
    mapping(address => uint256) public nonces;

    // Calculating the Permit typehash:
    bytes32 public constant PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");

    // Calculating the Delegated Transfer typehash:
    bytes32 public constant DELEGATED_TRANSFER_TYPEHASH =
        keccak256("DELEGATED_TRANSFER(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)");

    // Immutable variable for Domain Separator:
    // solhint-disable-next-line var-name-mixedcase
    bytes32 public DOMAIN_SEPARATOR;

    // A version number:
    // solhint-disable-next-line var-name-mixedcase
    string internal constant DOMAIN_SEPARATOR_VERSION = "1";

    /**
     * @dev Permit, approve via a sign message, using erc712.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        require(block.timestamp <= deadline, "ERC20Permit: expired deadline");

        bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        _checkOwner(owner, structHash, v, r, s);

        _approve(owner, spender, value);
    }

    /**
     * @dev Delegated Transfer, transfer via a sign message, using erc712.
     */
    function delegatedTransfer(
        address owner,
        address to,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        require(block.timestamp <= deadline, "ERC20Permit: expired deadline");

        bytes32 structHash = keccak256(abi.encode(DELEGATED_TRANSFER_TYPEHASH, owner, to, value, _useNonce(owner), deadline));

        _checkOwner(owner, structHash, v, r, s);

        _transfer(owner, to, value);
    }

    /**
     * @dev "Consume a nonce": return the current value and increment.
     */
    function _useNonce(address owner) internal virtual returns (uint256 current) {
        current = nonces[owner];
        nonces[owner]++;
    }

    function _checkOwner(address owner, bytes32 structHash, uint8 v, bytes32 r, bytes32 s) internal view {
        bytes32 hash = ECDSAUpgradeable.toTypedDataHash(DOMAIN_SEPARATOR, structHash);

        address signer = ECDSAUpgradeable.recover(hash, v, r, s);
        require(signer == owner, "ERC20Permit: invalid signature");
    }

    function _buildDomainSeparator() internal {
        DOMAIN_SEPARATOR = keccak256(
            abi.encode(
                keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                keccak256(bytes(name())),
                keccak256(bytes(DOMAIN_SEPARATOR_VERSION)),
                block.chainid,
                address(this)
            )
        );
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

contracts/SanctionsList.sol

pragma solidity 0.8.9;

/**
 * SPDX-License-Identifier: MIT
 *
 * Copyright (c) 2021-2022 Backed Finance AG
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

interface SanctionsList {
    function isSanctioned(address addr) external view returns (bool);
}

contracts/interfaces/IBackedAutoFeeToken.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;

import "../SanctionsList.sol";
import "./IBackedToken.sol";

/**
 * @title IBackedAutoFeeToken
 * @dev Interface for the BackedAutoFeeToken, a rebasing ERC20 token with automatic fee accrual
 *
 * This token implements a share-based rebasing mechanism where:
 * - Users hold shares that represent their portion of the total supply
 * - A multiplier converts shares to underlying token amounts
 * - Fees are automatically applied by decreasing the multiplier over time
 * - The multiplier can be updated by an authorized multiplierUpdater address
 */
interface IBackedAutoFeeToken is IBackedToken {
    /**
     * @dev Struct representing multiplier update
     * @param previousMultiplier The multiplier value before this update
     * @param newMultiplier The multiplier value after this update
     * @param activationTime The Unix timestamp when this update was/will be activated
     */
    struct MultiplierUpdate {
        uint256 previousMultiplier;
        uint256 newMultiplier;
        uint256 activationTime;
    }

    // Events

    /**
     * @dev Emitted when the multiplier updater address is changed
     * @param newMultiplierUpdater The address of the new multiplier updater
     */
    event NewMultiplierUpdater(address indexed newMultiplierUpdater);

    /**
     * @dev Emitted when shares are transferred between addresses
     * @param from The address shares are transferred from
     * @param to The address shares are transferred to
     * @param value The amount of shares transferred
     */
    event TransferShares(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the multiplier value is updated and activated
     * @param value The new multiplier value (in 1e18 precision)
     */
    event MultiplierUpdated(uint256 value);

    /**
     * @dev Emitted when a multiplier is scheduled for future activation
     * @param newMultiplier The new multiplier value that will be activated (in 1e18 precision)
     * @param activationTime The Unix timestamp when the multiplier will become active
     */
    event MultiplierScheduled(uint256 newMultiplier, uint256 activationTime);

    /**
     * @dev Emitted when a previously scheduled multiplier update is replaced
     * before its activationTime is reached. The overridden entry is removed
     * from `multiplierUpdates` in place and replaced by the new one.
     *
     * Off-chain consumers reconstructing state from events should drop any
     * earlier `MultiplierScheduled(overriddenMultiplier, overriddenActivationTime)`
     * upon seeing this event.
     *
     * @param overriddenMultiplier The newMultiplier of the pending entry that
     *        was discarded (the one previously announced via MultiplierScheduled)
     * @param overriddenActivationTime The activationTime of the discarded entry
     * @param newMultiplier The newMultiplier that replaces it (already announced
     *        in this same transaction via MultiplierScheduled or MultiplierUpdated)
     * @param newActivationTime The activationTime stored for the replacement
     */
    event MultiplierScheduleOverridden(
        uint256 overriddenMultiplier,
        uint256 overriddenActivationTime,
        uint256 newMultiplier,
        uint256 newActivationTime
    );

    // View functions - EIP-712 and Roles

    /**
     * @dev Returns the address authorized to update the multiplier
     * @return The multiplier updater address
     */
    function multiplierUpdater() external view returns (address);

    // View functions - Fee Configuration

    /**
     * @dev Returns the timestamp when the fee was last applied
     * @return The Unix timestamp of the last fee application
     */
    function lastTimeFeeApplied() external view returns (uint256);

    /**
     * @dev Returns the fee rate applied per period
     * @return The fee per period in 1e18 precision (e.g., 1e15 = 0.1% fee)
     */
    function feePerPeriod() external view returns (uint256);

    /**
     * @dev Returns the length of each fee accrual period in seconds
     * @return The period length in seconds (e.g., 86400 for daily fees)
     */
    function periodLength() external view returns (uint256);

    // View functions - Multiplier State

    /**
     * @dev Returns the last activated multiplier value
     * @return The last multiplier value in 1e18 precision
     */
    function lastMultiplier() external view returns (uint256);

    /**
     * @dev Returns the current active multiplier, considering pending activations
     * @return The currently active multiplier value in 1e18 precision
     */
    function multiplier() external view returns (uint256);

    /**
     * @dev Returns the nonce of the last activated multiplier
     * @return The last multiplier nonce
     */
    function lastMultiplierNonce() external view returns (uint256);

    /**
     * @dev Returns the nonce of the pending/new multiplier
     * @return The new multiplier nonce
     */
    function newMultiplierNonce() external view returns (uint256);

    /**
     * @dev Returns the value of the pending/new multiplier
     * @return The new multiplier value in 1e18 precision
     */
    function newMultiplier() external view returns (uint256);

    /**
     * @dev Returns the timestamp when the new multiplier becomes active
     * @return The Unix timestamp of activation (0 if no pending activation)
     */
    function newMultiplierActivationTime() external view returns (uint256);

    /**
     * @dev Returns the current multiplier nonce, considering pending activations
     * @return The current active multiplier nonce
     */
    function multiplierNonce() external view returns (uint256);

    /**
     * @dev Calculates and returns the current multiplier with fees applied
     * @return currentMultiplier The multiplier value with all accrued fees applied
     * @return periodsPassed The number of fee periods that have passed
     * @return currentMultiplierNonce The nonce including periods passed
     */
    function getCurrentMultiplier() external view returns (uint256 currentMultiplier, uint256 periodsPassed, uint256 currentMultiplierNonce);

    // View functions - Token Shares

    /**
     * @dev Returns the share balance of an account
     * @param account The address to query
     * @return The number of shares owned by the account
     */
    function sharesOf(address account) external view returns (uint256);

    /**
     * @dev Converts an underlying token amount to shares
     * @param _underlyingAmount The amount of tokens to convert
     * @return The equivalent amount of shares
     */
    function getSharesByUnderlyingAmount(uint256 _underlyingAmount) external view returns (uint256);

    /**
     * @dev Converts shares to underlying token amount
     * @param _sharesAmount The amount of shares to convert
     * @return The equivalent amount of tokens
     */
    function getUnderlyingAmountByShares(uint256 _sharesAmount) external view returns (uint256);

    /**
     * @dev Returns the length of the multiplierUpdates array.
     *
     * The array records *explicit* multiplier updates only (those submitted
     * via `updateMultiplierValue` / `updateMultiplierWithNonce`). Automatic
     * per-period fee decay is NOT appended. See `multiplierUpdates` for the
     * full semantics.
     *
     * @return The number of explicit multiplier updates stored
     *         (including the genesis sentinel at index 0).
     */
    function multiplierUpdatesLength() external view returns (uint256);

    /**
     * @dev Returns a specific explicit multiplier update by index.
     *
     * This array is an append-only log of *explicit* multiplier updates only;
     * automatic per-period fee decay is applied lazily to `lastMultiplier`
     * without appending here. As a result `previousMultiplier` at index `i`
     * is the fee-decayed value at the time of the i-th explicit update and
     * is typically less than `newMultiplier` at index `i-1` — the gap is the
     * accrual that happened in between.
     *
     * Index 0 is a genesis sentinel `{1e18, 1e18, 0}`. A future-dated entry
     * that is overridden before activation is popped from this array; the
     * `MultiplierScheduled` event for the popped entry remains on chain.
     *
     * @param index The index in the multiplierUpdates array
     * @return previousMultiplier The (possibly fee-decayed) multiplier value
     *         immediately before this explicit update was applied
     * @return newMultiplier The multiplier value after this update
     * @return activationTime The Unix timestamp when this update was/will be
     *         activated; equals `block.timestamp` at recording time for
     *         immediate updates, or the requested future timestamp for
     *         scheduled ones
     */
    function multiplierUpdates(uint256 index) external view returns (uint256 previousMultiplier, uint256 newMultiplier, uint256 activationTime);

    // State-changing functions - Share Transfers

    /**
     * @dev Executes a delegated share transfer using EIP-712 signature
     * @param owner The address that owns the shares
     * @param to The address to transfer shares to
     * @param value The amount of shares to transfer
     * @param deadline The deadline timestamp for the signature
     * @param v The recovery byte of the signature
     * @param r Half of the ECDSA signature pair
     * @param s Half of the ECDSA signature pair
     */
    function delegatedTransferShares(address owner, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;

    /**
     * @dev Transfers shares from the caller to another address
     * @param to The address to transfer shares to
     * @param sharesAmount The amount of shares to transfer
     * @return success True if the transfer succeeded
     */
    function transferShares(address to, uint256 sharesAmount) external returns (bool);

    /**
     * @dev Transfers shares from one address to another using allowance
     * @param from The address to transfer shares from
     * @param to The address to transfer shares to
     * @param sharesAmount The amount of shares to transfer
     * @return success True if the transfer succeeded
     */
    function transferSharesFrom(address from, address to, uint256 sharesAmount) external returns (bool);

    // State-changing functions - Fee Configuration (Owner only)

    /**
     * @dev Updates the fee rate per period
     * Can only be called by the owner
     * Cannot be called when a multiplier activation is pending
     * @param newFeePerPeriod The new fee rate in 1e18 precision
     */
    function updateFeePerPeriod(uint256 newFeePerPeriod) external;

    /**
     * @dev Updates the multiplier updater address
     * Can only be called by the owner
     * @param newMultiplierUpdater The address of the new multiplier updater
     */
    function setMultiplierUpdater(address newMultiplierUpdater) external;

    /**
     * @dev Updates the timestamp of last fee application
     * Can only be called by the owner
     * Cannot be called when a multiplier activation is pending
     * @param newLastTimeFeeApplied The new timestamp (must be non-zero)
     */
    function setLastTimeFeeApplied(uint256 newLastTimeFeeApplied) external;

    /**
     * @dev Updates the length of each fee period
     * Can only be called by the owner
     * Cannot be called when a multiplier activation is pending
     * @param newPeriodLength The new period length in seconds
     */
    function setPeriodLength(uint256 newPeriodLength) external;

    // State-changing functions - Multiplier Updates (Multiplier Updater only)

    /**
     * @dev Updates the multiplier value with automatic nonce increment
     * Can only be called by the multiplier updater
     * Validates that the oldMultiplier matches the current value
     * @param pendingNewMultiplier The new multiplier value in 1e18 precision
     * @param oldMultiplier The expected current multiplier for validation
     * @param pendingNewMultiplierActivationTime When to activate (0 for immediate, future timestamp for delayed)
     */
    function updateMultiplierValue(uint256 pendingNewMultiplier, uint256 oldMultiplier, uint256 pendingNewMultiplierActivationTime) external;

    /**
     * @dev Updates the multiplier value with explicit nonce
     * Can only be called by the multiplier updater
     * Validates that the oldMultiplier matches and nonce is newer
     * @param newMultiplier The new multiplier value in 1e18 precision
     * @param oldMultiplier The expected current multiplier for validation
     * @param newMultiplierNonce The explicit nonce for this update
     * @param pendingNewMultiplierActivationTime When to activate (0 for immediate, future timestamp for delayed)
     */
    function updateMultiplierWithNonce(uint256 newMultiplier, uint256 oldMultiplier, uint256 newMultiplierNonce, uint256 pendingNewMultiplierActivationTime) external;
}

contracts/interfaces/IBackedToken.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;

import "../SanctionsList.sol";

/**
 * @title IBackedToken
 * @dev Interface for BackedTokenImplementation, an ERC20 token with EIP-712
 *      permit and delegated-transfer support, role-based mint/burn/pause
 *      controls, a Chainalysis-compatible sanctions list, and a settable
 *      terms-of-service link.
 *
 * The contract exposes four roles:
 *  - minter: can mint new tokens.
 *  - burner: can burn its own tokens or tokens held by the contract itself.
 *  - pauser: can pause or unpause all transfers.
 *  - owner: can configure the three roles above, the sanctions list, the
 *           delegate-mode flags, and the terms string.
 */
interface IBackedToken {
    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);

    // View functions - Roles

    /**
     * @dev Returns the address authorized to mint tokens.
     */
    function minter() external view returns (address);

    /**
     * @dev Returns the address authorized to burn tokens.
     */
    function burner() external view returns (address);

    /**
     * @dev Returns the address authorized to pause/unpause transfers.
     */
    function pauser() external view returns (address);

    // View functions - Delegate Mode

    /**
     * @dev Returns whether anyone is allowed to relay `permit` and
     *      `delegatedTransfer` calls. When false, only addresses present in
     *      `delegateWhitelist` are allowed.
     */
    function delegateMode() external view returns (bool);

    /**
     * @dev Returns whether `account` is whitelisted to relay `permit` and
     *      `delegatedTransfer` calls.
     * @param account The address to query.
     */
    function delegateWhitelist(address account) external view returns (bool);

    // View functions - Pause

    /**
     * @dev Returns whether all token transfers are currently paused.
     */
    function isPaused() external view returns (bool);

    // View functions - Sanctions List and Terms

    /**
     * @dev Returns the sanctions list contract used to gate transfers and
     *      allowance spends. Follows the Chainalysis interface.
     */
    function sanctionsList() external view returns (SanctionsList);

    /**
     * @dev Returns the current terms-of-service string (typically a web or
     *      IPFS link).
     */
    function terms() external view returns (string memory);

    // State-changing functions - Initialization

    /**
     * @dev Initializes the token. Can only be called once per proxy.
     * @param name_   The ERC20 token name.
     * @param symbol_ The ERC20 token symbol.
     */
    function initialize(string memory name_, string memory symbol_) external;

    // State-changing functions - Mint and Burn

    /**
     * @dev Mint new tokens. Callable only by `minter`.
     * @param account Recipient of the minted tokens.
     * @param amount  Amount to mint.
     */
    function mint(address account, uint256 amount) external;

    /**
     * @dev Burn tokens. Callable only by `burner`. The burned tokens must
     *      come from the burner itself or from this contract.
     * @param account Account from which the tokens will be burned.
     * @param amount  Amount to burn.
     */
    function burn(address account, uint256 amount) external;

    // State-changing functions - Pause

    /**
     * @dev Pause or unpause all token transfers. Callable only by `pauser`.
     * @param newPauseMode True to pause, false to resume.
     */
    function setPause(bool newPauseMode) external;

    // State-changing functions - Owner Configuration

    /**
     * @dev Set the address authorized to mint tokens. Owner only.
     * @param newMinter The new minter address.
     */
    function setMinter(address newMinter) external;

    /**
     * @dev Set the address authorized to burn tokens. Owner only.
     * @param newBurner The new burner address.
     */
    function setBurner(address newBurner) external;

    /**
     * @dev Set the address authorized to pause transfers. Owner only.
     * @param newPauser The new pauser address.
     */
    function setPauser(address newPauser) external;

    /**
     * @dev Point the contract at a new sanctions-list contract. Owner only.
     *      The new contract must implement the Chainalysis interface; the
     *      call probes `isSanctioned(address(this))` to verify.
     * @param newSanctionsList The new sanctions list address.
     */
    function setSanctionsList(address newSanctionsList) external;

    /**
     * @dev Toggle the delegate-relay whitelist status of an address. Owner only.
     * @param whitelistAddress The address whose status is changing.
     * @param status           True to whitelist, false to remove.
     */
    function setDelegateWhitelist(address whitelistAddress, bool status) external;

    /**
     * @dev Toggle global delegate mode. When true, anyone may relay `permit`
     *      and `delegatedTransfer` calls. Owner only.
     * @param _delegateMode The new delegate-mode flag.
     */
    function setDelegateMode(bool _delegateMode) external;

    /**
     * @dev Set the terms-of-service string. Owner only.
     * @param newTerms The new terms (typically a web or IPFS link).
     */
    function setTerms(string memory newTerms) external;

    // Events

    event NewMinter(address indexed newMinter);
    event NewBurner(address indexed newBurner);
    event NewPauser(address indexed newPauser);
    event NewSanctionsList(address indexed newSanctionsList);
    event DelegateWhitelistChange(address indexed whitelistAddress, bool status);
    event DelegateModeChange(bool delegateMode);
    event PauseModeChange(bool pauseMode);
    event NewTerms(string newTerms);
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 10,
    "enabled": true
  },
  "evmVersion": "london",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.