CosigoSatellite

Description:

Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "CosigoSatellite.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

/*
 * cosigo_<town> — ERC20-like token (1 token = 1 mg), silver-backed policy gates
 * - Roles: owner (admin), custodian (ops/fee receiver), minter
 * - Fees: transfer maintenance fee (to feeSinkLocal if set), guardian skim on transfers
 * - Latch: redemption allowed only if floor(spot,premium) >= minFloor
 * - Deposits: register grams; maxSupply headroom = grams * 1000 * 1e18 minus (minted + pending + fulfilled)
 * - Guards: pause, blacklist, guardianChecks (approval + EOA-only + market-open)
 * - Daily redemption limiter; redemption registry + fulfill/cancel
 * - NEW:
 *    • burnSink (configurable) for park/hard-burn accounting
 *    • effectiveSupply(): totalSupply minus feeSinkLocal and burnSink balances
 *    • minRedemptionMg1e18 (0 = off)
 */

import "@openzeppelin/contracts@4.9.6/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts@4.9.6/token/ERC20/extensions/ERC20Permit.sol";
import "@openzeppelin/contracts@4.9.6/security/Pausable.sol";
import "@openzeppelin/contracts@4.9.6/access/AccessControl.sol";

import {ICosigoGuardian} from "./ICosigoGuardian.sol";
import {GuardianAware} from "./GuardianAware.sol";

contract CosigoSatellite is ERC20, ERC20Permit, Pausable, AccessControl, GuardianAware {
    // ---------- Constants & Roles ----------
    uint8   private constant DEC = 18;
    bytes32 public constant PAUSER_ROLE     = keccak256("PAUSER_ROLE");
    bytes32 public constant CUSTODIAN_ROLE  = keccak256("CUSTODIAN_ROLE");
    bytes32 public constant MINTER_ROLE     = keccak256("MINTER_ROLE");

    // Local hard caps (must also pass Guardian caps)
    uint16 public constant MAX_MAINTENANCE_FEE_BPS = 500;   // 5.00%
    uint16 public constant MAX_REDEMPTION_FEE_BPS  = 2500;  // 25.00%
    uint16 public constant MAX_PREMIUM_BPS         = 3000;  // 30.00%

    // Town slug policy (without "cosigo_" prefix)
    uint256 private constant MIN_SLUG_LEN = 4;
    uint256 private constant MAX_SLUG_LEN = 32;

    // Store slug only; ERC20 handles name/symbol
    string  public _slug;       // e.g., "queretaro"
    bytes32 public _slugHash;

    // ---------- Economics & caps ----------
    uint16 public maintenanceFeeBps; // transfer fee (to feeSinkLocal)
    uint16 public redemptionFeeBps;  // applied on redemption request (burned along with mg)
    uint16 public premiumBps;        // premium on spot for floor checks
    address public feeSinkLocal;     // local sink for maintenance fee (optional)

    // NEW: burn sink + effective supply
    address public burnSink;
    event BurnSinkSet(address sink);

    // NEW: minimum redemption (0 = off)
    uint256 public minRedemptionMg1e18;
    event MinRedemptionSet(uint256 mg1e18);

    // Sensitive setters timelock
    uint32 public paramTimelockSeconds = 0;
    mapping(bytes32 => uint64) public paramEta;

    // ---------- Custody & headroom accounting ----------
    struct Deposit { uint256 gramsMilli; bytes32 docHash; address depositor; uint64 ts; }
    Deposit[] public deposits;
    uint256 public totalGramsMilliDeposited;

    // Prevent burn-resurrection of headroom
    uint256 public mgFulfilled1e18; // shipped (fulfilled)
    uint256 public mgPending1e18;   // requested (burned mg), awaiting fulfill/cancel

    // ---------- Daily redemption caps ----------
    uint256 public dailyCapGlobalMg1e18;
    uint256 public dailyCapPerAddrMg1e18;

    struct Counter { uint256 amount; uint64 windowStart; }
    mapping(address => Counter) public redeemCounter;
    Counter public redeemCounterGlobal;

    // ---------- Blacklist ----------
    mapping(address => bool) public blacklisted;

    // ---------- Guardian upgrade (two-step) ----------
    address public proposedGuardian;
    uint64  public guardianChangeEta; // earliest accept time
    uint32  public guardianChangeDelay = 0;

    // ---------- Price/floor ----------
    uint256 public spotMicroCentsPerMg;     // settable
    uint256 public minFloorMicroCentsPerMg; // settable

    // ---------- Events ----------
    event DepositRegistered(uint256 idx, uint256 gramsMilli, bytes32 docHash, address depositor);
    event MintedAgainstHeadroom(address to, uint256 amountMg1e18, uint256 headroomAfter);
    event SpotSet(uint256 microCentsPerMg);
    event PremiumSet(uint16 bps);
    event MinFloorSet(uint256 microCentsPerMg);
    event MaintenanceFeeSet(uint16 bps);
    event RedemptionFeeSet(uint16 bps);
    event FeeSinkLocalSet(address sink);
    event RedemptionRequested(bytes32 id, address account, uint256 mg1e18, bytes32 ref);
    event RedemptionFulfilled(bytes32 id, string trackingHash);
    event RedemptionCancelled(bytes32 id, string reason);
    event RedemptionCapsSet(uint256 perAddrMg1e18, uint256 globalMg1e18);
    event GuardianFeeSkim(address from, address sink, uint256 fee, uint16 bps);
    event Blacklisted(address indexed acct, bool on, uint8 code);
    event ParamTimelockSet(uint32 seconds_);
    event GuardianProposed(address next, uint32 delay);
    event GuardianAccepted(address next);

    // ---------- Modifiers ----------
    modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "not admin"); _; }
    modifier onlyCustodian() { require(hasRole(CUSTODIAN_ROLE, msg.sender), "not custodian"); _; }
    modifier onlyMinter() { require(hasRole(MINTER_ROLE, msg.sender), "not minter"); _; }
    modifier notBlacklisted(address a) { require(!blacklisted[a], "blacklisted"); _; }

    // ---------- Constructor ----------
    // NOTE: takes ONLY the town slug (lowercase, a-z0-9). The contract builds "cosigo_<slug>".
    constructor(string memory town_, address guardian_)
        ERC20(string.concat("cosigo_", town_), string.concat("cosigo_", town_))
        ERC20Permit("cosigo_satellite")
        GuardianAware(guardian_)
    {
        // Validate slug
        bytes memory s = bytes(town_);
        require(s.length >= MIN_SLUG_LEN && s.length <= MAX_SLUG_LEN, "slug len");
        for (uint i = 0; i < s.length; ++i) {
            bytes1 c = s[i];
            bool ok = (c >= 0x61 && c <= 0x7a) || (c >= 0x30 && c <= 0x39); // a-z0-9
            require(ok, "slug char");
        }

        _slug = town_;
        _slugHash = keccak256(s);

        // Initial local admin/pauser = deployer
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _grantRole(PAUSER_ROLE,        msg.sender);
    }

    // ERC20 metadata: decimals
    function decimals() public pure override returns (uint8){ return DEC; }
    function slug() external view returns (string memory){ return _slug; }
    function slugHash() external view returns (bytes32){ return _slugHash; }

    // ---------- Param timelock helpers ----------
    function _pqueue(bytes32 id) internal { if (paramTimelockSeconds != 0) paramEta[id] = uint64(block.timestamp) + paramTimelockSeconds; }
    function _pcheck(bytes32 id) internal view {
        if (paramTimelockSeconds == 0) return;
        require(paramEta[id] != 0 && block.timestamp >= paramEta[id], "param timelock");
    }
    function _pclear(bytes32 id) internal { if (paramTimelockSeconds != 0) delete paramEta[id]; }
    function setParamTimelock(uint32 seconds_) external onlyAdmin {
        paramTimelockSeconds = seconds_;
        emit ParamTimelockSet(seconds_);
    }

    // ---------- Admin safety ----------
    function pause() external onlyRole(PAUSER_ROLE) { _pause(); }
    function unpause() external onlyRole(PAUSER_ROLE) { _unpause(); }
    function setBlacklist(address acct, bool on, uint8 code) external onlyAdmin {
        blacklisted[acct] = on; emit Blacklisted(acct, on, code);
    }

    // ---------- Economics (caps enforced: local AND Guardian) ----------
    function setMaintenanceFeeBps(uint16 bps) external onlyAdmin {
        require(bps <= MAX_MAINTENANCE_FEE_BPS, "local cap");
        require(bps <= guardian.maxMaintenanceFeeBps(), "guardian cap");
        bytes32 id = keccak256(abi.encode("setMaintenanceFee", bps)); _pqueue(id); _pcheck(id);
        maintenanceFeeBps = bps; _pclear(id); emit MaintenanceFeeSet(bps);
    }
    function setRedemptionFeeBps(uint16 bps) external onlyAdmin {
        require(bps <= MAX_REDEMPTION_FEE_BPS, "local cap");
        require(bps <= guardian.maxRedemptionFeeBps(), "guardian cap");
        bytes32 id = keccak256(abi.encode("setRedemptionFee", bps)); _pqueue(id); _pcheck(id);
        redemptionFeeBps = bps; _pclear(id); emit RedemptionFeeSet(bps);
    }
    function setPremiumBps(uint16 bps) external onlyAdmin {
        require(bps <= MAX_PREMIUM_BPS, "local cap");
        require(bps <= guardian.maxPremiumBps(), "guardian cap");
        bytes32 id = keccak256(abi.encode("setPremium", bps)); _pqueue(id); _pcheck(id);
        premiumBps = bps; _pclear(id); emit PremiumSet(bps);
    }
    function setSpotMicroCentsPerMg(uint256 x) external onlyAdmin {
        bytes32 id = keccak256(abi.encode("setSpot", x)); _pqueue(id); _pcheck(id);
        spotMicroCentsPerMg = x; _pclear(id); emit SpotSet(x);
    }
    function setMinFloorMicroCentsPerMg(uint256 x) external onlyAdmin {
        bytes32 id = keccak256(abi.encode("setFloor", x)); _pqueue(id); _pcheck(id);
        minFloorMicroCentsPerMg = x; _pclear(id); emit MinFloorSet(x);
    }
    function setFeeSinkLocal(address sink) external onlyAdmin { feeSinkLocal = sink; emit FeeSinkLocalSet(sink); }

    // NEW
    function setBurnSink(address sink) external onlyAdmin { burnSink = sink; emit BurnSinkSet(sink); }
    function setMinRedemption(uint256 mg1e18) external onlyAdmin { minRedemptionMg1e18 = mg1e18; emit MinRedemptionSet(mg1e18); }

    // ---------- Deposits & mint ----------
    function registerDeposit(uint256 gramsMilli, bytes32 docHash, address depositor)
        external onlyCustodian
    {
        require(gramsMilli > 0, "grams=0");
        require(docHash != bytes32(0), "docHash=0");
        deposits.push(Deposit({ gramsMilli: gramsMilli, docHash: docHash, depositor: depositor, ts: uint64(block.timestamp) }));
        totalGramsMilliDeposited += gramsMilli;
        emit DepositRegistered(deposits.length - 1, gramsMilli, docHash, depositor);
    }

    function depositsLength() external view returns (uint256) { return deposits.length; }

    function _depositedMg1e18() internal view returns (uint256) {
        // gramsMilli == mg units; then * 1e18 for token decimals
        return totalGramsMilliDeposited * 1e18;
    }

    function headroomMg1e18() public view returns (uint256) {
        uint256 dep = _depositedMg1e18();
        uint256 used = totalSupply() + mgPending1e18 + mgFulfilled1e18;
        if (dep <= used) return 0;
        return dep - used;
    }

    function effectiveSupply() public view returns (uint256) {
        uint256 s = totalSupply();
        if (feeSinkLocal != address(0)) s -= balanceOf(feeSinkLocal);
        if (burnSink    != address(0)) s -= balanceOf(burnSink);
        return s;
    }

    function mintAgainstHeadroom(address to, uint256 amountMg1e18)
        external onlyMinter
    {
        uint256 room = headroomMg1e18();
        require(amountMg1e18 <= room, "exceeds headroom");
        _mint(to, amountMg1e18);
        emit MintedAgainstHeadroom(to, amountMg1e18, room - amountMg1e18);
    }

    // ---------- Redemption flow ----------
    struct Redemption {
        address account;
        uint256 mg1e18;
        bytes32 ref; // opaque ref
        bool    fulfilled;
        bool    cancelled;
    }
    mapping(bytes32 => Redemption) public redemptions;

    function _rollCounter(Counter storage c, uint256 add) internal {
        uint64 start = c.windowStart;
        if (start == 0 || block.timestamp >= start + 1 days) {
            c.windowStart = uint64(block.timestamp);
            c.amount = add;
        } else {
            c.amount += add;
        }
    }

    function setRedemptionCaps(uint256 perAddrMg1e18, uint256 globalMg1e18) external onlyAdmin {
        dailyCapPerAddrMg1e18 = perAddrMg1e18;
        dailyCapGlobalMg1e18  = globalMg1e18;
        emit RedemptionCapsSet(perAddrMg1e18, globalMg1e18);
    }

    function _enforceCaps(address acct, uint256 mg1e18) internal {
        _rollCounter(redeemCounter[acct], mg1e18);
        require(dailyCapPerAddrMg1e18 == 0 || redeemCounter[acct].amount <= dailyCapPerAddrMg1e18, "per-addr cap");
        _rollCounter(redeemCounterGlobal, mg1e18);
        require(dailyCapGlobalMg1e18 == 0 || redeemCounterGlobal.amount <= dailyCapGlobalMg1e18, "global cap");
    }

    function redeemPhysicalSilver(uint256 mg1e18, bytes32 shippingRef)
        public whenNotPaused notBlacklisted(msg.sender) guardianChecks(msg.sender, address(0), mg1e18)
    {
        require(mg1e18 > 0, "zero mg");
        require(minRedemptionMg1e18 == 0 || mg1e18 >= minRedemptionMg1e18, "min redeem");
        _enforceCaps(msg.sender, mg1e18);

        // floor latch: (spot * (1 + premium)) >= minFloor
        if (minFloorMicroCentsPerMg > 0 && spotMicroCentsPerMg > 0) {
            uint256 eff = spotMicroCentsPerMg + (spotMicroCentsPerMg * premiumBps) / 10_000;
            require(eff >= minFloorMicroCentsPerMg, "floor not met");
        }

        // redemption fee (burned with mg for simple accounting)
        uint256 fee = (mg1e18 * redemptionFeeBps) / 10_000;
        uint256 burnAmount = mg1e18 + fee;
        _burn(msg.sender, burnAmount);

        // mark pending so headroom doesn't resurrect due to burn
        mgPending1e18 += mg1e18;

        // deterministic ID
        bytes32 id = keccak256(abi.encodePacked(msg.sender, mg1e18, shippingRef, block.number));
        redemptions[id] = Redemption({
            account: msg.sender, mg1e18: mg1e18, ref: shippingRef, fulfilled: false, cancelled: false
        });
        emit RedemptionRequested(id, msg.sender, mg1e18, shippingRef);
    }

    // convenience overload for front-ends
    function redeemPhysicalSilver(uint256 mg1e18, string calldata shippingRefStr) external {
        redeemPhysicalSilver(mg1e18, keccak256(bytes(shippingRefStr)));
    }

    function fulfillRedemption(bytes32 id, string calldata trackingHash)
        external onlyCustodian
    {
        Redemption storage r = redemptions[id];
        require(r.account != address(0), "bad id");
        require(!r.fulfilled && !r.cancelled, "done");
        r.fulfilled = true;

        mgPending1e18 -= r.mg1e18;
        mgFulfilled1e18 += r.mg1e18;

        emit RedemptionFulfilled(id, trackingHash);
    }

    function cancelRedemption(bytes32 id, string calldata reason)
        external onlyCustodian
    {
        Redemption storage r = redemptions[id];
        require(r.account != address(0), "bad id");
        require(!r.fulfilled && !r.cancelled, "done");
        r.cancelled = true;

        // return mg (fee remains burned)
        _mint(r.account, r.mg1e18);
        mgPending1e18 -= r.mg1e18;

        emit RedemptionCancelled(id, reason);
    }

    // ---------- Transfers with fees & guardian skim ----------
    function _transfer(address from, address to, uint256 amount)
        internal
        override
        whenNotPaused
        notBlacklisted(from)
        notBlacklisted(to)
        guardianChecks(from, to, amount)
    {
        uint256 amt = amount;

        // 1) Maintenance fee (local)
        if (maintenanceFeeBps > 0 && feeSinkLocal != address(0) && amount > 0 && from != address(0)) {
            uint256 f = (amount * maintenanceFeeBps) / 10_000;
            if (f > 0) {
                super._transfer(from, feeSinkLocal, f);
                amt -= f;
            }
        }

        // 2) Guardian skim
        uint16 gbps = _guardianFeeBps();
        address gsink = _guardianFeeSink();
        if (gbps > 0 && gsink != address(0) && amt > 0 && from != address(0)) {
            uint256 gf = (amt * gbps) / 10_000;
            if (gf > 0) {
                super._transfer(from, gsink, gf);
                emit GuardianFeeSkim(from, gsink, gf, gbps);
                amt -= gf;
            }
        }

        super._transfer(from, to, amt);
    }

    // for GuardianAware: fee settlement hook
    function _transferFee(address from, address sink, uint256 fee) internal override {
        if (fee == 0) return;
        super._transfer(from, sink, fee);
    }

    // ---------- Daily ops helpers ----------
    function grantLocalRoles(address custodianMS, address minter) external onlyAdmin {
        _grantRole(CUSTODIAN_ROLE, custodianMS);
        _grantRole(MINTER_ROLE,     minter);
    }

    // ---------- Guardian upgrade (two-step with delay) ----------
    function proposeGuardian(address next) external onlyAdmin {
        proposedGuardian = next;
        guardianChangeEta = uint64(block.timestamp) + guardianChangeDelay;
        emit GuardianProposed(next, guardianChangeDelay);
    }
    function acceptGuardian() external {
        require(msg.sender == proposedGuardian, "not proposed");
        require(block.timestamp >= guardianChangeEta, "delay");
        guardian = ICosigoGuardian(proposedGuardian);
        proposedGuardian = address(0);
        guardianChangeEta = 0;
        emit GuardianAccepted(address(guardian));
    }
    function setGuardianChangeDelay(uint32 seconds_) external onlyAdmin { guardianChangeDelay = seconds_; }

    // ---------- Rescue ----------
    function recoverERC20(address token, address to, uint256 amount) external onlyAdmin {
        require(token != address(this), "no self");
        (bool ok, bytes memory data) = token.call(abi.encodeWithSignature("transfer(address,uint256)", to, amount));
        require(ok && (data.length == 0 || abi.decode(data, (bool))), "transfer failed");
    }
}"
    },
    "GuardianAware.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

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

abstract contract GuardianAware {
    ICosigoGuardian public guardian;

    error GuardianNotApproved();
    error EOARequired();
    error MarketClosed();

    constructor(address guardian_) { guardian = ICosigoGuardian(guardian_); }

    modifier guardianChecks(address /*from*/, address /*to*/, uint256 /*amount*/) {
        if (!guardian.isSatelliteApproved(address(this))) revert GuardianNotApproved();
        if (guardian.eoaOnlyEnabled()) {
            if (tx.origin != msg.sender) revert EOARequired();
        }
        if (!guardian.isMarketOpen()) revert MarketClosed();
        _;
    }

    function _guardianFeeBps() internal view returns (uint16) {
        return guardian.guardianFeeBpsOf(address(this));
    }
    function _guardianFeeSink() internal view returns (address) {
        return guardian.feeSinkOf(address(this));
    }

    // ABSTRACT: implemented by the Satellite (which IS an ERC20)
    function _transferFee(address from, address sink, uint256 fee) internal virtual;

    // helper for transfer-like flows; returns net amount
    function _skimGuardianFee(address from, uint256 amount) internal returns (uint256) {
        uint16 bps = _guardianFeeBps();
        address sink = _guardianFeeSink();
        if (bps == 0 || sink == address(0) || amount == 0) return amount;
        uint256 fee = (amount * bps) / 10_000;
        if (fee > 0) _transferFee(from, sink, fee);
        return amount - fee;
    }
}"
    },
    "ICosigoGuardian.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

interface ICosigoGuardian {
    // Per-satellite policy
    function isSatelliteApproved(address sat) external view returns (bool);
    function feeSinkOf(address sat) external view returns (address);
    function guardianFeeBpsOf(address sat) external view returns (uint16);

    // Global signals
    function isMarketOpen() external view returns (bool);
    function eoaOnlyEnabled() external view returns (bool);

    // Global caps
    function maxGuardianFeeBps() external view returns (uint16);
    function maxMaintenanceFeeBps() external view returns (uint16);
    function maxRedemptionFeeBps() external view returns (uint16);
    function maxPremiumBps() external view returns (uint16);

    // Registry helpers
    function satelliteBySlug(bytes32 slugHash) external view returns (address);
}"
    },
    "@openzeppelin/contracts@4.9.6/access/AccessControl.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        Strings.toHexString(account),
                        " is missing role ",
                        Strings.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }
}
"
    },
    "@openzeppelin/contracts@4.9.6/security/Pausable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (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 Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        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());
    }
}
"
    },
    "@openzeppelin/contracts@4.9.6/token/ERC20/extensions/ERC20Permit.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/ERC20Permit.sol)

pragma solidity ^0.8.0;

import "./IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/cryptography/EIP712.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 constant _PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
    /**
     * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.
     * However, to ensure consistency with the upgradeable transpiler, we will continue
     * to reserve a slot.
     * @custom:oz-renamed-from _PERMIT_TYPEHASH
     */
    // solhint-disable-next-line var-name-mixedcase
    bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;

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

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

    /**
     * @inheritdoc IERC20Permit
     */
    function nonces(address owner) public view virtual override returns (uint256) {
        return _nonces[owner].current();
    }

    /**
     * @inheritdoc IERC20Permit
     */
    // 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();
    }
}
"
    },
    "@openzeppelin/contracts@4.9.6/token/ERC20/ERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

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

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

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

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

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

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

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

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

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

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

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

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

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

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

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

        return true;
    }

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

        _beforeTokenTransfer(from, to, amount);

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

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
"
    },
    "@openzeppelin/contracts@4.9.6/utils/Counters.sol": {
      "content": "// 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;
    }
}
"
    },
    "@openzeppelin/contracts@4.9.6/utils/cryptography/EIP712.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)

pragma solidity ^0.8.8;

import "./ECDSA.sol";
import "../ShortStrings.sol";
import "../../interfaces/IERC5267.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].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 *
 * _Available since v3.4._
 *
 * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
 */
abstract contract EIP712 is IERC5267 {
    using ShortStrings for *;

    bytes32 private constant _TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    // 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 _cachedDomainSeparator;
    uint256 private immutable _cachedChainId;
    address private immutable _cachedThis;

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

    ShortString private immutable _name;
    ShortString private immutable _version;
    string private _nameFallback;
    string private _versionFallback;

    /**
     * @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) {
        _name = name.toShortStringWithFallback(_nameFallback);
        _version = version.toShortStringWithFallback(_versionFallback);
        _hashedName = keccak256(bytes(name));
        _hashedVersion = keccak256(bytes(version));

        _cachedChainId = block.chainid;
        _cachedDomainSeparator = _buildDomainSeparator();
        _cachedThis = address(this);
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
            return _cachedDomainSeparator;
        } else {
            return _buildDomainSeparator();
        }
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, 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);
    }

    /**
     * @dev See {EIP-5267}.
     *
     * _Available since v4.9._
     */
    function eip712Domain()
        public
        view
        virtual
        override
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        return (
            hex"0f", // 01111
            _name.toStringWithFallback(_nameFallback),
            _version.toStringWithFallback(_versionFallback),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }
}
"
    },
    "@openzeppelin/contracts@4.9.6/utils/cryptography/ECDSA.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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 // Deprecated in v4.8
    }

    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");
        }
    }

    /**
     * @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) {
        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.
            /// @solidity memory-safe-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 {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

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

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

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

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

        // If 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 message) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\
32")
            mstore(0x1c, hash)
            message := keccak256(0x00, 0x3c)
        }
    }

    /**
     * @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 data) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, "\x19\x01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            data := keccak256(ptr, 0x42)
        }
    }

    /**
     * @d

Tags:
ERC20, ERC165, Proxy, Pausable, Voting, Timelock, Upgradeable, Factory|addr:0x859ccd70a83442257046db389c2ee94507c52748|verified:true|block:23587411|tx:0x65ca24f0fde1336c767ed103e7b24ec9d75cb45aff8367784212e8374e049238|first_check:1760604662

Submitted on: 2025-10-16 10:51:04

Comments

Log in to comment.

No comments yet.