Skip to content
Verified contractPartialMIT

BARK

Address0xd2c788d7f5aa583b740eb88abb5c64ebddc9d286
Balance

0 ETH

 

Transactions

26

 

Compiler

solc 0.8.19

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.19+commit.7dd6d404
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
23,232,010
Creation transaction
0x05eca8f01c…ecd0351dfb

2 files

Bark.sol

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

import "./EnumerableSet.sol";

abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

interface IERC20 {
    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address recipient, uint256 amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

interface IERC20Metadata is IERC20 {
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function decimals() external view returns (uint8);
}

contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;
    mapping(address => mapping(address => uint256)) private _allowances;
    uint256 private _totalSupply;
    string private _name;
    string private _symbol;

    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    function name() public view virtual override returns (string memory) {
        return _name;
    }

    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);

        uint256 currentAllowance = _allowances[sender][_msgSender()];
        require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
    unchecked {
        _approve(sender, _msgSender(), currentAllowance - amount);
    }

        return true;
    }

    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
        return true;
    }

    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        uint256 currentAllowance = _allowances[_msgSender()][spender];
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
            unchecked {
                _approve(_msgSender(), spender, currentAllowance - subtractedValue);
            }
        }
        return true;
    }

    function _transfer(
        address sender,
        address recipient,
        uint256 amount
    ) internal virtual {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");

        uint256 senderBalance = _balances[sender];
        require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
    unchecked {
        _balances[sender] = senderBalance - amount;
    }
        _balances[recipient] += amount;

        emit Transfer(sender, recipient, amount);
    }

    function _createInitialSupply(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);
    }

    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

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

contract Ownable is Context {
    address private _owner;

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

    constructor () {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

    function owner() public view returns (address) {
        return _owner;
    }

    modifier onlyOwner() {
        require(_owner == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    function renounceOwnership() external virtual onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = address(0);
    }

    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

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

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

    function addLiquidityETH(
        address token,
        uint256 amountTokenDesired,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    )
    external
    payable
    returns (
        uint256 amountToken,
        uint256 amountETH,
        uint256 liquidity
    );

    function getAmountsOut(
        uint amountIn,
        address[] calldata path
    ) external view returns (uint[] memory amounts);
}

interface IDexFactory {
    function createPair(address tokenA, address tokenB)
    external
    returns (address pair);
}

contract BARK is ERC20, Ownable {
    uint256 public maxSwapsPerBlock = 150;
    uint256 private swapsInCurrentBlock;
    uint256 private lastTradeBlock;

    event MaxSwapsPerBlockUpdated(uint256 newValue);

    uint256 public maxBuyAmount;

    IDexFactory public immutable uniswapV2Factory;
    IDexRouter public immutable uniswapV2Router;
    address public immutable uniswapV2Pair;
    address public immutable WETH;

    bool private swapping;
    uint256 public swapTokensAtAmount;
    uint256 public swapTokensLastBlock;

    address public treasuryAddress;

    uint256 public tradingActiveBlock = 0;
    uint256 public tradingActivatedAtTimestamp = 0;

    bool public limitsInEffect;
    bool public tradingActive;
    bool public swapFeesOncePerBlock;

    address public sniperBotsGuard;
    mapping(address => bool) public isSniperBot;

    uint256 public buyFee;
    uint256 public sellFee;

    mapping (address => bool) private _isExcludedFromFees;
    mapping (address => bool) public _isExcludedMaxTransactionAmount;
    mapping (address => bool) public automatedMarketMakerPairs;

    using EnumerableSet for EnumerableSet.AddressSet;
    EnumerableSet.AddressSet private _holders;

    event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
    event EnabledTrading();
    event RemovedLimits();

    event ExcludeFromFees(address indexed account, bool isExcluded);
    event UpdatedMaxBuyAmount(uint256 newAmount);
    event UpdatedTreasuryAddress(address indexed newWallet);
    event MaxTransactionExclusion(address _address, bool excluded);
    event SwapFeeCollected(uint256 amount);
    event SwapBackResult(uint256 amountIn, uint256 amountOut);
    event TransferForeignToken(address token, uint256 amount);
    event TreasuryTransferFailed(uint256 amount);

    event IsSniperBotSet(address account, bool isSniper);
    event SniperBotsGuardSet(address account);

    event SwapFeesOncePerBlockSet(bool newSetting);
    event SetSwapThreshold(uint256 newAmount);

    bool public maxSwapsPerBlockFreezeForever;

    function setSwapFeesOncePerBlock(bool newSetting) external {
        require(
            msg.sender == treasuryAddress || msg.sender == owner(),
            "only treasuryAddress or owner can change swapFeesOncePerBlock");
        swapFeesOncePerBlock = newSetting;
        emit SwapFeesOncePerBlockSet(newSetting);
    }

    bool public newSniperBotDisabledForever;
    event NewSniperBotDisabledForever();

    function disableNewSniperBotForever() external onlyOwner {
        newSniperBotDisabledForever = true;
        emit NewSniperBotDisabledForever();
    }

    function setSniperBot(address account, bool isSniper) external {
        require(
            msg.sender == sniperBotsGuard || msg.sender == owner(),
            "Only owner or sniperBotsGuard can set sniper bots");
        if (newSniperBotDisabledForever) {
            require(!isSniper, "New sniper bots are disabled forever");
        }
        isSniperBot[account] = isSniper;
        emit IsSniperBotSet(account, isSniper);
    }

    function setSniperBotsGuard(address account) external {
        require(
            msg.sender == owner() || msg.sender == sniperBotsGuard,
            "Only owner or sniperBotsGuard can set sniper bots guard");
        sniperBotsGuard = account;
        emit SniperBotsGuardSet(account);
    }

    constructor() ERC20('Bark', 'BARK') {
        address newOwner = msg.sender;
        sniperBotsGuard = newOwner;

        IDexRouter _uniswapV2Router = IDexRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
        _excludeFromMaxTransaction(address(_uniswapV2Router), true);
        uniswapV2Router = _uniswapV2Router;
        uniswapV2Factory = IDexFactory(_uniswapV2Router.factory());
        WETH = _uniswapV2Router.WETH();
        uniswapV2Pair = uniswapV2Factory.createPair(address(this), WETH);
        _setAutomatedMarketMakerPair(address(uniswapV2Pair), true);

        uint256 totalSupply = 1_000_000_000 * (10**18);

        maxBuyAmount = totalSupply * 70 / 100 / 100;  // 0.8% of total supply
        swapTokensAtAmount = totalSupply * 1 / 1_000_000;  // very small amount
        limitsInEffect = true;

        buyFee = 0 * 10000 / 100;
        sellFee = 0 * 10000 / 100;

        _excludeFromMaxTransaction(newOwner, true);
        _excludeFromMaxTransaction(address(this), true);
        _excludeFromMaxTransaction(address(0xdead), true);

        treasuryAddress = address(newOwner);

        excludeFromFees(newOwner, true);
        excludeFromFees(address(this), true);
        excludeFromFees(address(0xdead), true);
        excludeFromFees(treasuryAddress, true);

        _createInitialSupply(newOwner, totalSupply);
        // Add initial holder to holders list
        _updateHolderList(newOwner);
        transferOwnership(newOwner);
    }

    receive() external payable {}

    function updateMaxBuyAmount(uint256 newNum) external onlyOwner {
        require(newNum >= (totalSupply() * 1 / 1000) / 1e18, "Cannot set max buy amount lower than 0.1%");
        maxBuyAmount = newNum * (10**18);
        emit UpdatedMaxBuyAmount(maxBuyAmount);
    }

    function getFees() external view returns (uint256, uint256) {
        return (buyFee, sellFee);
    }

    bool public feesLocked = false;
    event FeesLocked();

    function lockFees() external onlyOwner {
        feesLocked = true;
        emit FeesLocked();
    }

    bool public feesOnlyLower = false;
    event FeesOnlyLower();

    function setFeesOnlyLower(bool _feesOnlyLower) external onlyOwner {
        feesOnlyLower = _feesOnlyLower;
        emit FeesOnlyLower();
    }

    function setFees(uint256 _buyFee, uint256 _sellFee) external onlyOwner {
        require(!feesLocked, "Fees are locked");
        require(_buyFee <= 10000 * 40 / 100, "High fee");
        require(_sellFee <= 10000 * 40 / 100, "High fee");
        if (feesOnlyLower) {
            require(_buyFee <= buyFee, "Buy fee can only be lowered");
            require(_sellFee <= sellFee, "Sell fee can only be lowered");
        }
        buyFee = _buyFee;
        sellFee = _sellFee;
    }

    function removeLimits() external onlyOwner {
        limitsInEffect = false;
        emit RemovedLimits();
    }

    function _excludeFromMaxTransaction(address updAds, bool isExcluded) private {
        _isExcludedMaxTransactionAmount[updAds] = isExcluded;
        emit MaxTransactionExclusion(updAds, isExcluded);
    }

    function excludeFromMaxTransaction(address updAds, bool isEx) external onlyOwner {
        if(!isEx){
            require(updAds != uniswapV2Pair, "Cannot remove uniswap pair from max txn");
        }
        _isExcludedMaxTransactionAmount[updAds] = isEx;
    }

    function setSwapThresholdUnits(uint256 newAmount) external {
        require(msg.sender == treasuryAddress || msg.sender == owner(),
            "only treasuryAddress or owner can change swapThreshold");
        swapTokensAtAmount = newAmount * 10**18;
        emit SetSwapThreshold(swapTokensAtAmount);
    }

    function transferForeignToken(address _token, address _to) public returns (bool _sent) {
        require(_token != address(0), "_token address cannot be 0");
        require(msg.sender == treasuryAddress,
            "only treasuryAddress can withdraw");
        uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
        _sent = IERC20(_token).transfer(_to, _contractBalance);
        emit TransferForeignToken(_token, _contractBalance);
    }

    function withdrawStuckETH() public {
        require(msg.sender == treasuryAddress, "only treasuryAddress can withdraw");
        bool success;
        (success,) = address(msg.sender).call{value: address(this).balance}("");
    }

    function excludeFromFees(address account, bool excluded) public onlyOwner {
        _isExcludedFromFees[account] = excluded;
        emit ExcludeFromFees(account, excluded);
    }

    function _getBuyFee() public view returns (uint256) {
        return buyFee;
    }

    function _getSellFee() public view returns (uint256) {
        return sellFee;
    }

    // ---------- Holders management ----------
    function _updateHolderList(address holder) internal {
        if (holder == address(0)) return;
        uint256 bal = balanceOf(holder);
        if (bal > 0) {
            _holders.add(holder);
        } else {
            _holders.remove(holder);
        }
    }

    function holdersLength() external view returns (uint256) {
        return _holders.length();
    }

    function holderByIndex(uint256 index) external view returns (address) {
        require(index < _holders.length(), "Index out of bounds");
        return _holders.at(index);
    }

    function holders() external view returns (address[] memory) {
        return _holders.values();
    }

    function _transfer(address from, address to, uint256 amount) internal override {

        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");
        require(amount > 0, "amount must be greater than 0");

        require(!isSniperBot[from] && !isSniperBot[to], "Sniper bots are not allowed");

        {
            uint256 currentBlock = block.number;
            if (currentBlock != lastTradeBlock) {
                swapsInCurrentBlock = 0;
                lastTradeBlock = currentBlock;
            }

            bool isBuy  = automatedMarketMakerPairs[from];
            bool isSell = automatedMarketMakerPairs[to];

            if (isBuy || isSell) {
                swapsInCurrentBlock += 1;
                require(maxSwapsPerBlock == 0 || swapsInCurrentBlock <= maxSwapsPerBlock,
                        "Max swaps per block exceeded");
            }
        }

        if(limitsInEffect){
            if (from != owner() && to != owner() && to != address(0) && to != address(0xdead)){
                if(!tradingActive){
                    require(_isExcludedMaxTransactionAmount[from] || _isExcludedMaxTransactionAmount[to], "Trading is not active.");
                    require(from == owner(), "Trading is not enabled");
                }
                //when buy
                if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
                    require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
                }
                //when sell
                else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
                }
                else if (!_isExcludedMaxTransactionAmount[to] && !_isExcludedMaxTransactionAmount[from]){
                }
            }
        }

        uint256 contractTokenBalance = balanceOf(address(this));

        bool canSwap = contractTokenBalance >= swapTokensAtAmount;

        if(
            canSwap &&
            tradingActive &&
            !swapping &&
            !automatedMarketMakerPairs[from] &&
            !_isExcludedFromFees[from] &&
            !_isExcludedFromFees[to]
        ) {
            swapping = true;
            _swapBack();
            swapping = false;
        }

        bool takeFee = true;
        // if any account belongs to _isExcludedFromFee account then remove the fee
        if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
            takeFee = false;
        }

        // only take fees on Trades, not on wallet transfers

        if(takeFee && tradingActiveBlock>0 && (block.number>tradingActiveBlock)) {
            uint256 fees = 0;

            // on sell
            if (automatedMarketMakerPairs[to] && _getSellFee() > 0) {
                fees = amount * _getSellFee() / 10000;
            }
            // on buy
            else if(automatedMarketMakerPairs[from] && _getBuyFee() > 0) {
                fees = amount * _getBuyFee() / 10000;
            }

            if(fees > 0){
                super._transfer(from, address(this), fees);
            }

            amount -= fees;

            emit SwapFeeCollected(fees);
        }

        super._transfer(from, to, amount);

        // Update holders list
        _updateHolderList(from);
        _updateHolderList(to);
        _updateHolderList(address(this));
    }

    function _swapTokensForEth(uint256 tokenAmount) private {
        // generate the uniswap pair path of token -> weth
        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = WETH;

        _approve(
            address(this), address(uniswapV2Router), tokenAmount);

        uint ethBalanceBeforeSwap = address(this).balance;

        // make the swap
        uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            tokenAmount,
            0, // accept any amount of ETH
            path,
            address(this),
            block.timestamp
        );
        emit SwapBackResult(tokenAmount, address(this).balance - ethBalanceBeforeSwap);
    }

    function setAutomatedMarketMakerPair(address pair, bool value) external onlyOwner {
        require(pair != uniswapV2Pair,
            "The pair cannot be removed from automatedMarketMakerPairs");

        _setAutomatedMarketMakerPair(pair, value);
    }

    function _setAutomatedMarketMakerPair(address pair, bool value) private {
        automatedMarketMakerPairs[pair] = value;

        _excludeFromMaxTransaction(pair, value);

        emit SetAutomatedMarketMakerPair(pair, value);
    }

    event SwapTokensLastBlockSet(uint256 newBlock);
    event SkipSwapBecauseOfBlock();

    uint256 public maxMilliEthForFeeSwapInTx = 1000;
    event MaxMilliEthForFeeSwapInTxUpdated(uint256 newMaxMilliEthForFeeSwapInTx);
    function setMaxMilliEthForFeeSwapInTx(uint256 newMaxMilliEthForFeeSwapInTx) external onlyOwner {
        maxMilliEthForFeeSwapInTx = newMaxMilliEthForFeeSwapInTx;
        emit MaxMilliEthForFeeSwapInTxUpdated(newMaxMilliEthForFeeSwapInTx);
    }

    bool public feeSellEnabled = false;
    event FeeSellEnabled();

    function enableFeeSell() external onlyOwner {
        feeSellEnabled = true;
        emit FeeSellEnabled();
    }

    function _swapBack() private {
        if ((tradingActivatedAtTimestamp != 0) || (!feeSellEnabled)) {
            return;
        }

        uint256 tokensToSwap = balanceOf(address(this));
        if(tokensToSwap == 0) {return;}

        if (swapFeesOncePerBlock && swapTokensLastBlock == block.number) {
            emit SkipSwapBecauseOfBlock();
            return;
        }
        swapTokensLastBlock = block.number;
        emit SwapTokensLastBlockSet(block.number);

        address[] memory _path = new address[](2);
        _path[0] = WETH;
        _path[1] = address(this);

        /* ------------------------------------------------------------------
           1) Per-transaction swap limit (maxMilliEthForFeeSwapInTx)
        ------------------------------------------------------------------ */
        if (maxMilliEthForFeeSwapInTx != 0) {
            uint256 maxWeiPerTx = maxMilliEthForFeeSwapInTx * 1e18 / 1000; // milli-ETH → wei
            uint256 _maxTokenAmountTx = uniswapV2Router.getAmountsOut(maxWeiPerTx, _path)[1];
            if (tokensToSwap > _maxTokenAmountTx) {
                tokensToSwap = _maxTokenAmountTx;
            }
        }

        if (tokensToSwap == 0) {return;}

        _swapTokensForEth(tokensToSwap);
        if (address(this).balance > 0) {
            uint256 contractEthBalance = address(this).balance;
            (bool success,) = address(treasuryAddress).call{value: contractEthBalance}("");
            if (!success) {
                // leave ETH on contract; will attempt again on next swap
                emit TreasuryTransferFailed(contractEthBalance);
            }
        }
    }

    function makeManualSwap() external {
        require(_msgSender() == treasuryAddress,
            "Only treasuryAddress can manually swap");
        uint256 tokenBalance = balanceOf(address(this));
        if(tokenBalance > 0){
            swapping = true;
            _swapBack();
            swapping = false;
        }
    }

    // once enabled, can never be turned off
    function enableTrading() external onlyOwner {
        require(!tradingActive, "Cannot re enable trading");
        tradingActive = true;
        emit EnabledTrading();
        tradingActiveBlock = block.number;
        tradingActivatedAtTimestamp = block.timestamp;
    }

    function setMaxTotalSwapsPerBlock(uint256 newValue) external onlyOwner {
        require(!maxSwapsPerBlockFreezeForever, "forever freeze is enabled");
        maxSwapsPerBlock = newValue;
        emit MaxSwapsPerBlockUpdated(newValue);
    }

    function freezeMaxSwapsPerBlockForever() external onlyOwner {
        maxSwapsPerBlockFreezeForever = true;
    }
}

EnumerableSet.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            if (lastIndex != toDeleteIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}
Compiler settingsShow
{
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.