Skip to content
Verified contractExact

EcoZeroProposal

Address0x07d88e7e2a7cce2db87be4764e36f9172cf15767
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.19

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.19+commit.7dd6d404
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
License
Not stated
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
21,720,820
Creation transaction
0xd6f1de88ed…1f16294e95

57 files

src/3_Eco_Zero_Proposal/EcoZeroProposal.sol

import {Proposal} from "currency-1.5/governance/community/proposals/Proposal.sol";
import {ECO} from "currency-1.5/currency/ECO.sol";
import {L1ECOBridge} from "op-eco/bridge/L1ECOBridge.sol";


contract EcoZeroProposal is Proposal {
    
    //L1 contracts
    address public immutable newECOImpl;
    ECO public immutable eco;
    L1ECOBridge public immutable l1ECOBridge;
    
    //L2 contracts
    address public immutable newL2ECOImpl;

    //other
    uint32 public immutable l2gas;

    constructor(
        address _newECOImpl,
        address _newL2ECOImpl,
        L1ECOBridge _l1ECOBridge,
        ECO _eco,
        uint32 _l2gas
        ) {
        newECOImpl = _newECOImpl;
        newL2ECOImpl = _newL2ECOImpl;
        l1ECOBridge = _l1ECOBridge;
        eco = _eco;
        l2gas = _l2gas;
    }

    function name() public pure virtual override returns (string memory) {
        return "Zero Eco Balances";
    }

    function description()
        public
        pure
        virtual
        override
        returns (string memory)
    {
        return
            "Zeros Eco Balances in Advance of Token Migration";
    }

    function url() public pure override returns (string memory) {
        return
            "N/A";
    }

    function enacted(address _self) public virtual override{
        eco.setImplementation(newECOImpl);
        l1ECOBridge.upgradeECO(newL2ECOImpl, l2gas);
    }

}  

lib/currency-1.5/contracts/currency/DelegatePermit.sol

// SPDX-License-Identifier: MIT
// Heavily inspired by:
// OpenZeppelin Contracts v4.4.1 (token/Delegate/extensions/draft-ERC20Permit.sol)

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";

/**
 * Abstract contract including helper functions to allow delegation by signature using
 * [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612).
 *
 * Adds the `{_verifyDelegatePermit}` internal method, verifies a signature specifying permission to receive delegation power
 *
 */
abstract contract DelegatePermit is EIP712 {
    using Counters for Counters.Counter;

    mapping(address => Counters.Counter) private _nonces;

    // solhint-disable-next-line var-name-mixedcase
    bytes32 private constant _DELEGATE_TYPEHASH =
        keccak256(
            "Delegate(address delegator,address delegatee,uint256 nonce,uint256 deadline)"
        );

    /**
     * Verify that the given delegate signature is valid, throws if not
     * @param delegator The address delegating
     * @param delegatee The address being delegated to
     * @param deadline The deadling of the delegation after which it will be invalid
     * @param v The v part of the signature
     * @param r The r part of the signature
     * @param s The s part of the signature
     */
    function _verifyDelegatePermit(
        address delegator,
        address delegatee,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        require(
            block.timestamp <= deadline,
            "DelegatePermit: expired deadline"
        );
        require(delegator != address(0), "invalid delegator");

        bytes32 structHash = keccak256(
            abi.encode(
                _DELEGATE_TYPEHASH,
                delegator,
                delegatee,
                _useDelegationNonce(delegator),
                deadline
            )
        );

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        require(signer == delegator, "DelegatePermit: invalid signature");
    }

    /**
     * get the current nonce for the given address
     * @param owner The address to get nonce for
     * @return nonce current nonce of `owner`
     */
    function delegationNonce(
        address owner
    ) public view returns (uint256 nonce) {
        nonce = _nonces[owner].current();
        return nonce;
    }

    /**
     * "Consume a nonce": return the current value and increment.
     *
     * Available since v4.1.
     * @param owner The address to consume a nonce for
     * @return current incremented nonce of `owner`
     */
    function _useDelegationNonce(
        address owner
    ) private returns (uint256 current) {
        Counters.Counter storage nonce = _nonces[owner];
        current = nonce.current();
        nonce.increment();
        return current;
    }
}

lib/currency-1.5/contracts/currency/ECO.sol

/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./InflationSnapshots.sol";
import "../governance/monetary/CurrencyGovernance.sol";

/**
 * @title An ERC20 token interface to the Eco currency system.
 */
contract ECO is InflationSnapshots {
    //////////////////////////////////////////////
    //////////////////// VARS ////////////////////
    //////////////////////////////////////////////

    /**
     * Mapping storing contracts able to rebase the token
     */
    mapping(address => bool) public rebasers;
    /**
     * Mapping storing contracts able to rebase the token
     */
    mapping(address => bool) public snapshotters;

    //////////////////////////////////////////////
    /////////////////// ERRORS ///////////////////
    //////////////////////////////////////////////

    /**
     * error for when an address tries to rebase without permission
     */
    error OnlyRebasers();

    /**
     * error for when an address tries to snapshot without permission
     */
    error OnlySnapshotters();

    //////////////////////////////////////////////
    /////////////////// EVENTS ///////////////////
    //////////////////////////////////////////////

    /**
     * emits when the rebasers permissions are changed
     * @param actor denotes the new address whose permissions are being updated
     * @param newPermission denotes the new ability of the actor address (true for can rebase, false for cannot)
     */
    event UpdatedRebasers(address actor, bool newPermission);

    /**
     * emits when the snapshotters permissions are changed
     * @param actor denotes the new address whose permissions are being updated
     * @param newPermission denotes the new ability of the actor address (true for can snapshot, false for cannot)
     */
    event UpdatedSnapshotters(address actor, bool newPermission);

    //////////////////////////////////////////////
    ////////////////// MODIFIERS /////////////////
    //////////////////////////////////////////////

    /**
     * Modifier for checking if the sender is a rebaser
     */
    modifier onlyRebaserRole() {
        if (!rebasers[msg.sender]) {
            revert OnlyRebasers();
        }
        _;
    }

    /**
     * Modifier for checking if the sender is a snapshotter
     */
    modifier onlySnapshotterRole() {
        if (!snapshotters[msg.sender]) {
            revert OnlySnapshotters();
        }
        _;
    }

    //////////////////////////////////////////////
    ///////////////// CONSTRUCTOR ////////////////
    //////////////////////////////////////////////

    constructor(
        Policy _policy,
        address _initialPauser
    ) InflationSnapshots(_policy, "ECO", "ECO", _initialPauser) {}

    //////////////////////////////////////////////
    ///////////////// INITIALIZER ////////////////
    //////////////////////////////////////////////

    function initialize(
        address _self
    ) public virtual override onlyConstruction {
        super.initialize(_self);
        pauser = ERC20Pausable(_self).pauser();
    }

    //////////////////////////////////////////////
    ////////////////// FUNCTIONS /////////////////
    //////////////////////////////////////////////

    /**
     * Rebase the currency using an inflation multiplier
     * @param _inflationMultiplier the multipler used to rebase the currency
     */
    function rebase(uint256 _inflationMultiplier) public onlyRebaserRole {
        _rebase(_inflationMultiplier);
    }

    /**
     * Creates a new snapshot
     */
    function snapshot() public onlySnapshotterRole {
        _snapshot();
    }

    /**
     * change the rebasing permissions for an address
     * only callable by tokenRoleAdmin
     * @param _key the address to change permissions for
     * @param _value the new permission. true = can rebase, false = cannot rebase
     */
    function updateRebasers(address _key, bool _value) public onlyPolicy {
        rebasers[_key] = _value;
        emit UpdatedRebasers(_key, _value);
    }

    /**
     * change the rebasing permissions for an address
     * only callable by tokenRoleAdmin
     * @param _key the address to change permissions for
     * @param _value the new permission. true = can snapshot, false = cannot snapshot
     */
    function updateSnapshotters(address _key, bool _value) public onlyPolicy {
        snapshotters[_key] = _value;
        emit UpdatedSnapshotters(_key, _value);
    }
}

lib/currency-1.5/contracts/currency/ECOx.sol

/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IECO.sol";
import "./TotalSupplySnapshots.sol";

/**
 * @title An ERC20 token interface for ECOx
 *
 */
contract ECOx is TotalSupplySnapshots {
    //////////////////////////////////////////////
    //////////////////// VARS ////////////////////
    //////////////////////////////////////////////

    /**
     * @dev Mapping storing contracts able to rebase the token
     */
    mapping(address => bool) public snapshotters;

    //////////////////////////////////////////////
    /////////////////// ERRORS ///////////////////
    //////////////////////////////////////////////

    /**
     * error for when transfer returns false
     * used by contracts that import this contract
     */
    error TransferFailed();

    /**
     * error for when an address tries to snapshot without permission
     */
    error OnlySnapshotters();

    //////////////////////////////////////////////
    /////////////////// EVENTS ///////////////////
    //////////////////////////////////////////////

    /**
     * emits when the snapshotters permissions are changed
     * @param actor denotes the new address whose permissions are being updated
     * @param newPermission denotes the new ability of the actor address (true for can snapshot, false for cannot)
     */
    event UpdatedSnapshotters(address actor, bool newPermission);

    //////////////////////////////////////////////
    ////////////////// MODIFIERS /////////////////
    //////////////////////////////////////////////

    /**
     * @dev Modifier for checking if the sender is a snapshotter
     */
    modifier onlySnapshotterRole() {
        if (!snapshotters[msg.sender]) {
            revert OnlySnapshotters();
        }
        _;
    }

    constructor(
        Policy _policy,
        address _pauser
    ) TotalSupplySnapshots(_policy, "ECOx", "ECOx", _pauser) {}

    function initialize(
        address _self
    ) public virtual override onlyConstruction {
        super.initialize(_self);
        pauser = ERC20Pausable(_self).pauser();
    }

    function snapshot() public onlySnapshotterRole {
        _snapshot();
    }

    /**
     * @dev change the rebasing permissions for an address
     * only callable by tokenRoleAdmin
     * @param _key the address to change permissions for
     * @param _value the new permission. true = can snapshot, false = cannot snapshot
     */
    function updateSnapshotters(address _key, bool _value) public onlyPolicy {
        snapshotters[_key] = _value;
        emit UpdatedSnapshotters(_key, _value);
    }
}

lib/currency-1.5/contracts/currency/ERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../utils/StringPacker.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./ERC20Permit.sol";

/**
 * Implementation of the {IERC20} interface.
 *
 * This comment taken from the openzeppelin source contract.
 *
 * 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 open zeppelin guide
 * [How to implement supply mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).
 *
 * 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}.
 */
// internal _name and _symbol are stored immutable as bytes32 and unpacked via StringPacker
contract ERC20 is ERC20Permit {
    mapping(address => uint256) internal _balances;

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

    uint256 internal _totalSupply;

    bytes32 internal immutable _name;
    bytes32 internal immutable _symbol;

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

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

    /**
     * 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_) ERC20Permit(name_) {
        _name = StringPacker.pack(name_);
        _symbol = StringPacker.pack(symbol_);
    }

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

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

    /**
     * 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 returns (uint8) {
        return 18;
    }

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

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

    /**
     * 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 returns (bool) {
        _transfer(msg.sender, recipient, amount);
        return true;
    }

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

    /**
     * See {IERC20-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(
        address spender,
        uint256 amount
    ) public virtual returns (bool) {
        _approve(msg.sender, spender, amount);
        return true;
    }

    /**
     * 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 returns (bool) {
        _transfer(sender, recipient, amount);

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

        return true;
    }

    /**
     * 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(
            msg.sender,
            spender,
            _allowances[msg.sender][spender] + addedValue
        );
        return true;
    }

    /**
     * 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[msg.sender][spender];
        require(
            currentAllowance >= subtractedValue,
            "ERC20: decreased allowance below zero"
        );
        unchecked {
            _approve(msg.sender, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * 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 originalAmount
    ) internal virtual {
        require(recipient != address(0), "ERC20: transfer to the zero address");

        uint256 amount = _beforeTokenTransfer(
            sender,
            recipient,
            originalAmount
        );

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

        emit Transfer(sender, recipient, originalAmount);

        _afterTokenTransfer(sender, recipient, amount);
    }

    /** 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 originalAmount
    ) internal virtual returns (uint256) {
        require(account != address(0), "ERC20: mint to the zero address");

        uint256 amount = _beforeTokenTransfer(
            address(0),
            account,
            originalAmount
        );

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

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

        return amount;
    }

    /**
     * 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 originalAmount
    ) internal virtual returns (uint256) {
        uint256 amount = _beforeTokenTransfer(
            account,
            address(0),
            originalAmount
        );

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

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

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

        return amount;
    }

    /**
     * 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 override {
        require(spender != address(0), "ERC20: approve to the zero address");

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

    /**
     * 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 returns (uint256) {
        return amount;
    }

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

lib/currency-1.5/contracts/currency/ERC20Delegated.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./ERC20Pausable.sol";
import "./DelegatePermit.sol";
import "./TotalSupplySnapshots.sol";

/**
 * This contract tracks delegations of an ERC20 token by tokenizing the delegations
 * It assumes a companion token that is transferred to denote changes in votes brought
 * on by both transfers (via _afterTokenTransfer hooks) and delegations.
 * The secondary token creates allowances whenever it delegates to allow for reclaiming the voting power later
 *
 * Voting power can be queried through the public accessor {voteBalanceOf}. Vote power can be delegated either
 * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}.
 * Delegates need to disable their own ability to delegate to enable others to delegate to them.
 *
 * Raw delegations can be done in partial amounts via {delegateAmount}. This is intended for contracts which can run
 * their own internal ledger of delegations and will prevent you from transferring the delegated funds until you undelegate.
 */
abstract contract ERC20Delegated is TotalSupplySnapshots, DelegatePermit {
    // this checks who has opted in to voting
    mapping(address => bool) public voter;

    // this balance tracks the amount of votes an address has for snapshot purposes
    mapping(address => uint256) internal _voteBalances;

    // allowances are created to allow for undelegation and to track delegated amounts
    mapping(address => mapping(address => uint256)) private _voteAllowances;

    // total allowances helps track if an account is delegated
    // its value is equivalent to agregating across the middle value of the previous mapping
    mapping(address => uint256) private _totalVoteAllowances;

    /** a mapping that tracks the primaryDelegates of each user
     *
     * Primary delegates can only be chosen using delegate() which sends the full balance
     * The exist to maintain the functionality that recieving tokens gives those votes to the delegate
     */
    mapping(address => address) internal _primaryDelegates;

    // mapping that tracks if an address is willing to be delegated to
    mapping(address => bool) public delegationToAddressEnabled;

    // mapping that tracks if an address is unable to delegate
    mapping(address => bool) public delegationFromAddressDisabled;

    /**
     * Emitted when a delegatee is delegated new votes.
     */
    event DelegatedVotes(
        address indexed delegator,
        address indexed delegatee,
        uint256 amount
    );

    /**
     * Emitted when a token transfer or delegate change results a transfer of voting power.
     */
    event VoteTransfer(
        address indexed sendingVoter,
        address indexed recievingVoter,
        uint256 votes
    );

    /**
     * Emitted when an account denotes a primary delegate.
     */
    event NewPrimaryDelegate(
        address indexed delegator,
        address indexed primaryDelegate
    );

    constructor(
        Policy _policy,
        string memory _name,
        string memory _symbol,
        address _initialPauser
    ) TotalSupplySnapshots(_policy, _name, _symbol, _initialPauser) {
        // call to super constructor
    }

    function enableVoting() public {
        require(!voter[msg.sender], "ERC20Delegated: voting already enabled");

        voter[msg.sender] = true; // this must be set before the mint to make sure voting power is given
        _voteMint(msg.sender, _balances[msg.sender]);
    }

    /**
     * Set yourself as willing to recieve delegates.
     */
    function enableDelegationTo() public {
        require(
            isOwnDelegate(msg.sender),
            "ERC20Delegated: cannot enable delegation if you have outstanding delegation"
        );

        require(
            voter[msg.sender],
            "ERC20Delegated: enable voting before enabling being a delegate"
        );

        delegationToAddressEnabled[msg.sender] = true;
        delegationFromAddressDisabled[msg.sender] = true;
    }

    /**
     * Set yourself as no longer recieving delegates.
     */
    function disableDelegationTo() public {
        delegationToAddressEnabled[msg.sender] = false;
    }

    /**
     * Set yourself as being able to delegate again.
     * also disables delegating to you
     */
    function reenableDelegating() public {
        delegationToAddressEnabled[msg.sender] = false;

        require(
            _balances[msg.sender] == _voteBalances[msg.sender] &&
                isOwnDelegate(msg.sender),
            "ERC20Delegated: cannot re-enable delegating if you have outstanding delegations"
        );

        delegationFromAddressDisabled[msg.sender] = false;
    }

    /**
     * Returns true if the user has no amount of their balance delegated, otherwise false.
     */
    function isOwnDelegate(address account) public view returns (bool) {
        return
            _totalVoteAllowances[account] == 0 &&
            _primaryDelegates[account] == address(0);
    }

    /**
     * Get the primary address `account` is currently delegating to. Defaults to the account address itself if none specified.
     * The primary delegate is the one that is delegated any new funds the address recieves.
     * @param account the address whose primary delegate is being fetched
     */
    function getPrimaryDelegate(
        address account
    ) public view virtual returns (address) {
        address _voter = _primaryDelegates[account];
        return _voter == address(0) ? account : _voter;
    }

    /**
     * sets the primaryDelegate and emits an event to track it
     */
    function _setPrimaryDelegate(
        address delegator,
        address delegatee
    ) internal {
        _primaryDelegates[delegator] = delegatee;

        emit NewPrimaryDelegate(
            delegator,
            delegatee == address(0) ? delegator : delegatee
        );
    }

    /**
     * Delegate all votes from the sender to `delegatee`.
     * NOTE: This function assumes that you do not have partial delegations
     * It will revert with "ERC20Delegated: must have an undelegated amount available to cover delegation" if you do
     * @param delegatee the address being delegated to
     */
    function delegate(address delegatee) public {
        require(
            delegatee != msg.sender,
            "ERC20Delegated: use undelegate instead of delegating to yourself"
        );

        require(
            delegationToAddressEnabled[delegatee],
            "ERC20Delegated: a primary delegate must enable delegation"
        );

        if (!isOwnDelegate(msg.sender)) {
            undelegateFromAddress(getPrimaryDelegate(msg.sender));
        }

        uint256 _amount = _balances[msg.sender];
        _delegate(msg.sender, delegatee, _amount);
        _setPrimaryDelegate(msg.sender, delegatee);
    }

    /**
     * Delegate all votes from the sender to `delegatee`.
     * NOTE: This function assumes that you do not have partial delegations
     * It will revert with "ERC20Delegated: must have an undelegated amount available to cover delegation" if you do
     * @param delegator the address delegating votes
     * @param delegatee the address being delegated to
     * @param deadline the time at which the signature expires
     * @param v signature value
     * @param r signature value
     * @param s signature value
     */
    function delegateBySig(
        address delegator,
        address delegatee,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public {
        require(
            delegator != delegatee,
            "ERC20Delegated: use undelegate instead of delegating to yourself"
        );
        require(
            delegationToAddressEnabled[delegatee],
            "ERC20Delegated: a primary delegate must enable delegation"
        );

        if (!isOwnDelegate(delegator)) {
            _undelegateFromAddress(delegator, getPrimaryDelegate(delegator));
        }

        _verifyDelegatePermit(delegator, delegatee, deadline, v, r, s);

        uint256 _amount = _balances[delegator];
        _delegate(delegator, delegatee, _amount);
        _setPrimaryDelegate(delegator, delegatee);
    }

    /**
     * Delegate an `amount` of votes from the sender to `delegatee`.
     */
    function delegateAmount(address delegatee, uint256 amount) public {
        require(
            delegatee != msg.sender,
            "ERC20Delegated: use undelegate instead of delegating to yourself"
        );
        require(
            delegatee != address(0),
            "ERC20Delegated: cannot delegate to the zero address"
        );

        _delegate(msg.sender, delegatee, amount);
    }

    /**
     * Change delegation for `delegator` to `delegatee`.
     *
     * Emits events {NewDelegatedAmount} and {VoteTransfer}.
     */
    function _delegate(
        address delegator,
        address delegatee,
        uint256 amount
    ) internal virtual {
        require(
            voter[delegator],
            "ERC20Delegated: must be a voter to delegate"
        );

        // more strict that the transfer requirement
        require(
            amount <= _balances[delegator] - _totalVoteAllowances[delegator],
            "ERC20Delegated: must have an undelegated amount available to cover delegation"
        );

        require(
            !delegationFromAddressDisabled[delegator],
            "ERC20Delegated: cannot delegate if you have enabled primary delegation to yourself and/or have outstanding delegates"
        );

        emit DelegatedVotes(delegator, delegatee, amount);

        _voteTransfer(delegator, delegatee, amount);
        // create allowance to reclaim token
        _increaseVoteAllowance(delegatee, delegator, amount);
        // track owed votes
        _totalVoteAllowances[delegator] += amount;
    }

    /**
     * Undelegate all votes from the sender's primary delegate.
     */
    function undelegate() public {
        address _primaryDelegate = getPrimaryDelegate(msg.sender);
        require(
            _primaryDelegate != msg.sender,
            "ERC20Delegated: must specifiy undelegate address when not using a Primary Delegate"
        );
        undelegateFromAddress(_primaryDelegate);
    }

    /**
     * Undelegate votes from the `delegatee` back to the sender.
     */
    function undelegateFromAddress(address delegatee) public {
        _undelegateFromAddress(msg.sender, delegatee);
    }

    /**
     * A primary delegated individual can revoke delegations of unwanted delegators
     * Useful for allowing yourself to call reenableDelegating after calling disableDelegationTo
     * @param delegator the address whose delegation is being revoked
     */
    function revokeDelegation(address delegator) public {
        address _primaryDelegate = getPrimaryDelegate(delegator);
        require(
            (delegator != msg.sender) && (_primaryDelegate == msg.sender),
            "ERC20Delegated: can only revoke delegations to yourself"
        );
        _undelegateFromAddress(delegator, msg.sender);
    }

    /**
     * Undelegate votes from the `delegatee` back to the delegator.
     */
    function _undelegateFromAddress(
        address delegator,
        address delegatee
    ) internal {
        uint256 _amount = voteAllowance(delegatee, delegator);
        _undelegate(delegator, delegatee, _amount);
        if (delegatee == getPrimaryDelegate(delegator)) {
            _setPrimaryDelegate(delegator, address(0));
        }
    }

    /**
     * Undelegate a specific amount of votes from the `delegatee` back to the sender.
     * @param delegatee the address being undelegated to
     * @param amount the amount of tokens being undelegated
     */
    function undelegateAmountFromAddress(
        address delegatee,
        uint256 amount
    ) public {
        require(
            voteAllowance(delegatee, msg.sender) >= amount,
            "ERC20Delegated: amount not available to undelegate"
        );
        require(
            msg.sender == getPrimaryDelegate(msg.sender),
            "ERC20Delegated: undelegating amounts is only available for partial delegators"
        );
        _undelegate(msg.sender, delegatee, amount);
    }

    function _undelegate(
        address delegator,
        address delegatee,
        uint256 amount
    ) internal virtual {
        _totalVoteAllowances[delegator] -= amount;
        _voteTransferFrom(delegatee, delegator, amount);
    }

    /**
     * Move voting power when tokens are transferred.
     *
     * Emits a {VoteTransfer} event.
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual override {
        if (from == to) {
            // self transfers require no change in delegation and can be the source of exploits
            return;
        }

        bool fromVoter = voter[from];

        // if the address has delegated, they might be transfering tokens allotted to someone else
        if (fromVoter && !isOwnDelegate(from)) {
            address _sourcePrimaryDelegate = _primaryDelegates[from]; // cheaper than getPrimaryDelegate because we do the check to own delegate already
            if (_sourcePrimaryDelegate == address(0)) {
                // this combined with !isOwnDelegate(from) guarantees a partial delegate situation
                uint256 _undelegatedAmount = _balances[from] + // need to check if the transfer can be covered
                    amount -
                    _totalVoteAllowances[from];
                require(
                    _undelegatedAmount >= amount, // can't undelegate in a partial delegate situation
                    "ERC20Delegated: delegation too complicated to transfer. Undelegate and simplify before trying again"
                );
            } else {
                // the combination of !isOwnDelegate(from) and _sourcePrimaryDelegate != address(0) means that we're in a primary delegate situation where all funds are delegated
                // this means that we already know that amount < _sourcePrimaryDelegatement since _sourcePrimaryDelegatement == senderBalance
                _undelegate(from, _sourcePrimaryDelegate, amount);
            }
        }

        if (voter[to]) {
            address _voteDestination = to;
            address _destPrimaryDelegate = _primaryDelegates[to];
            // saving gas by manually doing a form of isOwnDelegate since this function already needs to read the data for this conditional
            if (_destPrimaryDelegate != address(0)) {
                _increaseVoteAllowance(_destPrimaryDelegate, to, amount);
                _totalVoteAllowances[to] += amount;
                _voteDestination = _destPrimaryDelegate;
            }

            if (fromVoter) {
                _voteTransfer(from, _voteDestination, amount);
            } else {
                _voteMint(_voteDestination, amount);
            }
        } else {
            if (fromVoter) {
                _voteBurn(from, amount);
            }
        }
    }

    /**
     * See {IERC20-balanceOf}.
     * @param account the address whose vote balance is being checked
     */
    function voteBalanceOf(
        address account
    ) public view virtual returns (uint256) {
        return _voteBalances[account];
    }

    /**
     * See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `recipient` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function voteTransfer(
        address recipient,
        uint256 amount
    ) internal virtual returns (bool) {
        _voteTransfer(msg.sender, recipient, amount);
        return true;
    }

    /**
     * See {IERC20-allowance}.
     */
    function voteAllowance(
        address owner,
        address spender
    ) internal view virtual returns (uint256) {
        return _voteAllowances[owner][spender];
    }

    /**
     * See {IERC20-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function voteApprove(
        address spender,
        uint256 amount
    ) internal virtual returns (bool) {
        _voteApprove(msg.sender, spender, amount);
        return true;
    }

    /**
     * not the same as ERC20 transferFrom
     * is instead more restrictive, only allows for transfers where the recipient owns the allowance
     */
    function _voteTransferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) internal virtual returns (bool) {
        _voteTransfer(sender, recipient, amount);

        uint256 currentAllowance = _voteAllowances[sender][recipient];
        require(
            currentAllowance >= amount,
            "ERC20Delegated: vote transfer amount exceeds allowance"
        );
        unchecked {
            _voteApprove(sender, recipient, currentAllowance - amount);
        }

        return true;
    }

    /**
     * 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 _voteTransfer(
        address sender,
        address recipient,
        uint256 amount
    ) internal virtual {
        _beforeVoteTokenTransfer(sender, recipient, amount);

        if (sender != address(0)) {
            uint256 senderBalance = _voteBalances[sender];
            require(
                senderBalance >= amount,
                "ERC20Delegated: vote transfer amount exceeds balance"
            );
            unchecked {
                _voteBalances[sender] = senderBalance - amount;
            }
        }

        if (recipient != address(0)) {
            _voteBalances[recipient] += amount;
        }

        emit VoteTransfer(sender, recipient, amount);

        _afterVoteTokenTransfer(sender, recipient, amount);
    }

    /** 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 _voteMint(
        address account,
        uint256 amount
    ) internal virtual returns (uint256) {
        require(
            account != address(0),
            "ERC20Delegated: vote mint to the zero address"
        );

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

        _voteBalances[account] += amount;
        emit VoteTransfer(address(0), account, amount);

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

        return amount;
    }

    /**
     * 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 _voteBurn(
        address account,
        uint256 amount
    ) internal virtual returns (uint256) {
        _beforeVoteTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _voteBalances[account];
        require(
            accountBalance >= amount,
            "ERC20Delegated: vote burn amount exceeds balance"
        );
        unchecked {
            _voteBalances[account] = accountBalance - amount;
        }

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

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

        return amount;
    }

    /**
     * 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 _voteApprove(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(
            spender != address(0),
            "ERC20Delegate: approve votes to the zero address"
        );

        _voteAllowances[owner][spender] = amount;
    }

    /**
     * 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 _increaseVoteAllowance(
        address owner,
        address spender,
        uint256 addedValue
    ) internal virtual returns (bool) {
        _voteApprove(
            owner,
            spender,
            _voteAllowances[owner][spender] + addedValue
        );
        return true;
    }

    /**
     * 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 _decreaseVoteAllowance(
        address owner,
        address spender,
        uint256 subtractedValue
    ) internal virtual returns (bool) {
        uint256 currentAllowance = _voteAllowances[owner][spender];
        require(
            currentAllowance >= subtractedValue,
            "ERC20Delegated: decreased vote allowance below zero"
        );
        unchecked {
            _voteApprove(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * 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.
     */
    function _beforeVoteTokenTransfer(
        address, // from
        address, // to
        uint256 amount
    ) internal virtual {}

    /**
     * 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.
     */
    function _afterVoteTokenTransfer(
        address, // from
        address, // to
        uint256 amount
    ) internal virtual {}

    // protecting future upgradeability
    uint256[50] private __gapERC20Delegated;
}

lib/currency-1.5/contracts/currency/ERC20MintAndBurn.sol

/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../policy/PolicedUpgradeable.sol";
import "./ERC20Pausable.sol";

/**
 * @title An ERC20 token interface for ECOx
 *
 */
contract ERC20MintAndBurn is ERC20Pausable, PolicedUpgradeable {
    // storage gap covers all of ECO contract's old delegation functionality (no ECOx storage to be gapped)
    uint256[10] private __gapMintAndBurn;
    // additional useable gap for future upgradeability
    uint256[50] private __gapMintAndBurn2;
    //////////////////////////////////////////////
    //////////////////// VARS ////////////////////
    //////////////////////////////////////////////
    /**
     * Mapping storing contracts able to mint tokens
     */
    mapping(address => bool) public minters;

    /**
     * Mapping storing contracts able to burn tokens
     */
    mapping(address => bool) public burners;

    //////////////////////////////////////////////
    /////////////////// ERRORS ///////////////////
    //////////////////////////////////////////////

    /**
     * error for when an address tries to mint tokens without permission
     */
    error OnlyMinters();

    /**
     * error for when an address tries to burn tokens without permission
     */
    error OnlyBurners();

    //////////////////////////////////////////////
    /////////////////// EVENTS ///////////////////
    //////////////////////////////////////////////

    /**
     * emits when the minters permissions are changed
     * @param actor denotes the new address whose permissions are being updated
     * @param newPermission denotes the new ability of the actor address (true for can mint, false for cannot)
     */
    event UpdatedMinters(address actor, bool newPermission);

    /**
     * emits when the burners permissions are changed
     * @param actor denotes the new address whose permissions are being updated
     * @param newPermission denotes the new ability of the actor address (true for can burn, false for cannot)
     */
    event UpdatedBurners(address actor, bool newPermission);

    //////////////////////////////////////////////
    ////////////////// MODIFIERS /////////////////
    //////////////////////////////////////////////

    /**
     * Modifier for checking if the sender is a minter
     */
    modifier onlyMinterRole() {
        if (!minters[msg.sender]) {
            revert OnlyMinters();
        }
        _;
    }

    /**
     * Modifier for checking if the sender is allowed to burn
     * both burners and the message sender can burn
     * @param _from the address burning tokens
     */
    modifier onlyBurnerRoleOrSelf(address _from) {
        if (_from != msg.sender && !burners[msg.sender]) {
            revert OnlyBurners();
        }
        _;
    }

    constructor(
        Policy policy,
        string memory name,
        string memory ticker,
        address pauser
    ) Policed(policy) ERC20Pausable(name, ticker, address(policy), pauser) {}

    /**
     * change the minting permissions for an address
     * only callable by tokenRoleAdmin
     * @param _key the address to change permissions for
     * @param _value the new permission. true = can mint, false = cannot mint
     */
    function updateMinters(address _key, bool _value) public onlyPolicy {
        minters[_key] = _value;
        emit UpdatedMinters(_key, _value);
    }

    /**
     * change the burning permissions for an address
     * only callable by tokenRoleAdmin
     * @param _key the address to change permissions for
     * @param _value the new permission. true = can burn, false = cannot burn
     */
    function updateBurners(address _key, bool _value) public onlyPolicy {
        burners[_key] = _value;
        emit UpdatedBurners(_key, _value);
    }

    /**
     * mints tokens to a given address
     * @param _to the address receiving tokens
     * @param _value the amount of tokens being minted
     */
    function mint(address _to, uint256 _value) external onlyMinterRole {
        _mint(_to, _value);
    }

    /**
     * burns tokens to a given address
     * @param _from the address whose tokens are being burned
     * @param _value the amount of tokens being burned
     */
    function burn(
        address _from,
        uint256 _value
    ) external onlyBurnerRoleOrSelf(_from) {
        _burn(_from, _value);
    }

    // protecting future upgradeability
    uint256[50] private __gapMintAndBurn3;
}

lib/currency-1.5/contracts/currency/ERC20Pausable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/security/Pausable.sol";
import "./ERC20.sol";

/**
 * Implementation of the {IERC20} interface with pausability
 * When paused by the pauser admin, transfers revert.
 */
contract ERC20Pausable is ERC20, Pausable {
    address public immutable roleAdmin;

    // initially no-one should have the pauser role
    // it can be granted and revoked by the admin policy
    address public pauser;

    /**
     * @notice event indicating the pauser was updated
     * @param pauser The new pauser
     */
    event PauserAssignment(address indexed pauser);

    constructor(
        string memory name,
        string memory symbol,
        address _roleAdmin,
        address _initialPauser
    ) ERC20(name, symbol) {
        require(
            address(_roleAdmin) != address(0),
            "Unrecoverable: do not set the _roleAdmin as the zero address"
        );
        roleAdmin = _roleAdmin;
        pauser = _initialPauser;
        emit PauserAssignment(_initialPauser);
    }

    modifier onlyAdmin() {
        require(msg.sender == roleAdmin, "ERC20Pausable: not admin");
        _;
    }

    modifier onlyPauser() {
        require(msg.sender == pauser, "ERC20Pausable: not pauser");
        _;
    }

    /**
     * Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * If the token is not paused, it will pass through the amount
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual override whenNotPaused returns (uint256) {
        return amount;
    }

    /**
     * @notice pauses transfers of this token
     *
     * Security Notes
     *
     * - only callable by the pause
     * - reverts if already paused
     */
    function pause() external onlyPauser {
        _pause();
    }

    /**
     * @notice unpauses transfers of this token
     * only callable by the pauser
     *
     * Security Notes
     *
     * - only callable by the pause
     * - reverts if already unpaused
     */
    function unpause() external onlyPauser {
        _unpause();
    }

    /**
     * @notice set the given address as the pauser
     * @param _pauser The address that can pause this token
     * only the roleAdmin can call this function
     */
    function setPauser(address _pauser) public onlyAdmin {
        require(_pauser != pauser, "ERC20Pausable: must change pauser");
        pauser = _pauser;
        emit PauserAssignment(_pauser);
    }
}

lib/currency-1.5/contracts/currency/ERC20Permit.sol

// SPDX-License-Identifier: MIT
// Heavily inspired by:
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";

/**
 * Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * [EIP-2612](https://eips.ethereum.org/EIPS/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 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)"
        );

    /**
     * Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"2"`.
     *
     * version number 1 was used already in a previous implementation
     */
    constructor(string memory name) EIP712(name, "2") {
        //empty block in order to pass parameters to the parent EIP712 constructor
    }

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

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

    /**
     * See {IERC20Permit-DOMAIN_SEPARATOR}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view override returns (bytes32) {
        return _domainSeparatorV4();
    }

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

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

lib/currency-1.5/contracts/currency/IECO.sol

/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

interface IECO is IERC20 {
    /**
     * Only available to minters
     * @param to the address to mint to
     * @param amount the amount to mint
     */
    function mint(address to, uint256 amount) external;

    /**
     * Only available to token holders for their own tokens and burners
     * @param from the address to burn from
     * @param amount the amount to burn
     */
    function burn(address from, uint256 amount) external;

    /**
     * Returns the votes for the current snapshot
     * @param account the address whose vote balance to check
     * @return balance the balance of the account at the time of the Snapshot
     */
    function voteBalanceSnapshot(
        address account
    ) external view returns (uint256 balance);

    /**
     * Returns the inflation multiplier value for the current snapshot
     * @return multiplier inflation multipler value
     */
    function inflationMultiplierSnapshot()
        external
        view
        returns (uint256 multiplier);

    /**
     *  Returns the total supply for the current snapshot
     * @return total total supply of the current snapshot
     */
    function totalSupplySnapshot() external view returns (uint256 total);

    /**
     * Enables voting with your ECO balance, but will transaction cost
     */
    function enableVoting() external;

    /**
     * Allows others to delegate voting power to you
     * Disallows you from delegating your voting power to others
     */
    function enableDelegationTo() external;

    /**
     * Disallows others from delegating to you
     * Does not change your ability to delegate to others
     */
    function disableDelegationTo() external;

    /**
     * Allows others to delegate to you
     * Disallows you from delegating to others
     */
    function reenableDelegating() external;

    /**
     * Returns true if the address has no amount of their balance delegated, otherwise false
     * @param account the address whose delegation status is being checked
     */
    function isOwnDelegate(address account) external returns (bool);

    /**
     * Fetches the primary address `account` is currently delegating to. Defaults to the account address itself if none specified.
     * The primary delegate is the one that is delegated any new funds the address recieves
     * @param account the address whose primary delegate is being fetched
     */
    function getPrimaryDelegate(
        address account
    ) external view returns (address);

    /**
     * Delegates all votes from the sender to `delegatee`
     * This function assumes that you do not have partial delegations
     * It will revert with "ERC20Delegated: must have an undelegated amount available to cover delegation" if you do
     * @param delegatee the address being delegated to
     */
    function delegate(address delegatee) external;

    /**
     * Delegates all votes from the sender to `delegatee`
     * This function assumes that you do not have partial delegations
     * It will revert with "ERC20Delegated: must have an undelegated amount available to cover delegation" if you do
     * @param delegator the address delegating votes
     * @param delegatee the address being delegated to
     * @param deadline the time at which the signature expires
     * @param v signature value
     * @param r signature value
     * @param s signature value
     */
    function delegateBySig(
        address delegator,
        address delegatee,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * Delegate an `amount` of votes from the sender to `delegatee`
     * @param delegatee the address being delegated to
     * @param amount the amount of tokens being allocated
     */
    function delegateAmount(address delegatee, uint256 amount) external;

    /**
     * Undelegate all votes from the sender's primary delegate
     */
    function undelegate() external;

    /**
     * Allows a primary delegated individual to revoke delegations of unwanted delegators
     * Useful for allowing yourself to call reenableDelegating after calling disableDelegationTo
     * @param delegator the address whose delegation is being revoked
     */
    function revokeDelegation(address delegator) external;

    /**
     * Undelegate a specific amount of votes from the `delegatee` back to the sender
     * @param delegatee the address being undelegated to
     * @param amount the amount of tokens being undelegated
     */
    function undelegateAmountFromAddress(
        address delegatee,
        uint256 amount
    ) external;

    /**
     * See {IERC20-balanceOf}.
     * @param account the address whose vote balance is being checked
     */
    function voteBalanceOf(address account) external view returns (uint256);
}

lib/currency-1.5/contracts/currency/InflationSnapshots.sol

/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./VoteSnapshots.sol";

/**
 * @title InflationSnapshots
 * @notice This implements a scaling inflation multiplier on all balances and votes.
 * Changing this value (via implementing _rebase)
 */
abstract contract InflationSnapshots is VoteSnapshots {
    uint256 public constant INITIAL_INFLATION_MULTIPLIER = 1e18;

    Snapshot internal _inflationMultiplierSnapshot;

    uint256 public inflationMultiplier;

    /**
     * error for when a rebase attempts to rebase incorrectly
     */
    error BadRebaseValue();

    /**
     * Fired when a proposal with a new inflation multiplier is selected and passed.
     * Used to calculate new values for the rebased token.
     * @param adjustinginflationMultiplier the multiplier that has just been applied to the tokens
     * @param cumulativeInflationMultiplier the total multiplier that is used to convert to and from gons
     */
    event NewInflationMultiplier(
        uint256 adjustinginflationMultiplier,
        uint256 cumulativeInflationMultiplier
    );

    /**
     * to be used to record the transfer amounts after _beforeTokenTransfer
     * these values are the base (unchanging) values the currency is stored in
     * @param from address transferring from
     * @param to address transferring to
     * @param value the base value being transferred
     */
    event BaseValueTransfer(
        address indexed from,
        address indexed to,
        uint256 value
    );

    /** Construct a new instance.
     * Note that it is always necessary to call reAuthorize on the balance store
     * after it is first constructed to populate the authorized interface
     * contracts cache. These calls are separated to allow the authorized
     * contracts to be configured/deployed after the balance store contract.
     * @param _policy the Policy
     * @param _name the token name
     * @param _symbol the token symbol
     * @param _initialPauser the initial Pauser
     */
    constructor(
        Policy _policy,
        string memory _name,
        string memory _symbol,
        address _initialPauser
    ) VoteSnapshots(_policy, _name, _symbol, _initialPauser) {
        inflationMultiplier = INITIAL_INFLATION_MULTIPLIER;
        _updateInflationSnapshot();
    }

    /**
     * Initialize
     * @param _self the address to initialize
     */
    function initialize(
        address _self
    ) public virtual override onlyConstruction {
        super.initialize(_self);
        inflationMultiplier = INITIAL_INFLATION_MULTIPLIER;
        _updateInflationSnapshot();
    }

    function _rebase(uint256 _inflationMultiplier) internal virtual {
        if (_inflationMultiplier == 0) {
            revert BadRebaseValue();
        }

        // update snapshot with old value
        _updateInflationSnapshot();

        uint256 newInflationMult = (_inflationMultiplier *
            inflationMultiplier) / INITIAL_INFLATION_MULTIPLIER;

        inflationMultiplier = newInflationMult;

        emit NewInflationMultiplier(_inflationMultiplier, newInflationMult);
    }

    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual override returns (uint256) {
        amount = super._beforeTokenTransfer(from, to, amount);
        uint256 gonsAmount = amount * inflationMultiplier;

        emit BaseValueTransfer(from, to, gonsAmount);

        return gonsAmount;
    }

    /**
     * Inflation Multiplier Snapshot
     * @return inflationValueMultiplier Inflation Value Muliplier at time of the Snapshot
     */
    function inflationMultiplierSnapshot()
        public
        view
        returns (uint256 inflationValueMultiplier)
    {
        if (
            currentSnapshotBlock != block.number &&
            _inflationMultiplierSnapshot.snapshotBlock < currentSnapshotBlock
        ) {
            return inflationMultiplier;
        } else {
            return _inflationMultiplierSnapshot.value;
        }
    }

    /**
     * wrapper for inflationMultiplierSnapshot to maintain compatability with older interfaces
     * no requires even though return value might be misleading given inability to query old snapshots just to maintain maximum compatability
     * @return pastLinearInflationMultiplier Inflation Value Muliplier at time of the Snapshot
     */
    function getPastLinearInflation(
        uint256
    ) public view returns (uint256 pastLinearInflationMultiplier) {
        return inflationMultiplier;
    }

    /**
     * Access function to determine the token balance held by some address.
     * @param _owner address of the owner of the voting balance
     * @return inflationBalance value of the owner divided by the inflation multiplier
     */
    function balanceOf(
        address _owner
    ) public view override returns (uint256 inflationBalance) {
        return _balances[_owner] / inflationMultiplier;
    }

    /**
     * Access function to determine the voting balance (includes delegation) of some address.
     * @param _owner the address of the account to get the balance for
     * @return votingBalance The vote balance fo the owner divided by the inflation multiplier
     */
    function voteBalanceOf(
        address _owner
    ) public view override returns (uint256 votingBalance) {
        return _voteBalances[_owner] / inflationMultiplier;
    }

    /**
     * Returns the total (inflation corrected) token supply
     * @return totalInflatedSupply The total supply divided by the inflation multiplier
     */
    function totalSupply()
        public
        view
        override
        returns (uint256 totalInflatedSupply)
    {
        return _totalSupply / inflationMultiplier;
    }

    /**
     * Returns the total (inflation corrected) token supply for the current snapshot
     * @return totalInflatedSupply The total supply snapshot divided by the inflation multiplier
     */
    function totalSupplySnapshot()
        public
        view
        override
        returns (uint256 totalInflatedSupply)
    {
        return super.totalSupplySnapshot() / inflationMultiplierSnapshot();
    }

    /**
     * Return snapshotted voting balance (includes delegation) for the current snapshot.
     * @param account The account to check the votes of.
     * @return snapshotted voting balance (includes delegation) for the current snapshot.
     */
    function voteBalanceSnapshot(
        address account
    ) public view override returns (uint256) {
        uint256 _inflationMultiplier = inflationMultiplierSnapshot();

        if (_inflationMultiplier == 0) {
            return 0;
        }

        return super.voteBalanceSnapshot(account) / _inflationMultiplier;
    }

    function _updateInflationSnapshot() private {
        uint32 _currentSnapshotBlock = currentSnapshotBlock;
        // take no action during the snapshot block, only after it
        if (_currentSnapshotBlock == block.number) {
            return;
        }

        if (
            _inflationMultiplierSnapshot.snapshotBlock < _currentSnapshotBlock
        ) {
            uint256 currentValue = inflationMultiplier;
            require(
                currentValue <= type(uint224).max,
                "InflationSnapshots: new snapshot cannot be casted safely"
            );
            _inflationMultiplierSnapshot.snapshotBlock = _currentSnapshotBlock;
            _inflationMultiplierSnapshot.value = uint224(currentValue);
        }
    }

    // protecting future upgradeability
    uint256[50] private __gapInflationSnapshots;
}

lib/currency-1.5/contracts/currency/TotalSupplySnapshots.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./ERC20MintAndBurn.sol";

/**
 * @dev Basic snapshotting just for total supply.
 *
 * This extension maintains a snapshot the total supply which updates on mint or burn after a new snapshot is taken.
 */
abstract contract TotalSupplySnapshots is ERC20MintAndBurn {
    // structure for saving snapshotted values
    struct Snapshot {
        uint32 snapshotBlock;
        uint224 value;
    }

    // the reference snapshotBlock that the update function checks against
    uint32 public currentSnapshotBlock;

    // the snapshot to track the token total supply
    Snapshot internal _totalSupplySnapshot;

    /**
     * @dev Emitted by {_snapshot} when a new snapshot is created.
     *
     * @param block the new value of currentSnapshotBlock
     */
    event NewSnapshotBlock(uint256 block);

    constructor(
        Policy _policy,
        string memory _name,
        string memory _symbol,
        address _initialPauser
    ) ERC20MintAndBurn(_policy, _name, _symbol, _initialPauser) {
        // snapshot on creation to make it clear that everyone's balances should be updated
        _snapshot();
    }

    function initialize(
        address _self
    ) public virtual override onlyConstruction {
        super.initialize(_self);
        // snapshot on initialization to make it clear that everyone's balances should be updated after upgrade
        _snapshot();
    }

    /**
     * @dev Retrieve the `totalSupply` for the snapshot
     */
    function totalSupplySnapshot() public view virtual returns (uint256) {
        if (
            currentSnapshotBlock != block.number &&
            _totalSupplySnapshot.snapshotBlock < currentSnapshotBlock
        ) {
            return _totalSupply;
        } else {
            return _totalSupplySnapshot.value;
        }
    }

    /**
     * Update total supply snapshots before the values are modified. This is implemented
     * in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual override returns (uint256) {
        if (from == address(0)) {
            // mint
            _updateTotalSupplySnapshot();
        } else if (to == address(0)) {
            // burn
            _updateTotalSupplySnapshot();
        }

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

    /**
     * @dev Creates a new snapshot and returns its snapshot id.
     *
     * Emits a {NewSnapshotBlock} event that contains the same id.
     */
    function _snapshot() internal virtual {
        // the math will error if the snapshot overflows
        currentSnapshotBlock = uint32(block.number);

        emit NewSnapshotBlock(block.number);
    }

    function _updateTotalSupplySnapshot() private {
        uint32 _currentSnapshotBlock = currentSnapshotBlock;
        // take no action during the snapshot block, only after it
        if (_currentSnapshotBlock == block.number) {
            return;
        }

        if (_totalSupplySnapshot.snapshotBlock < _currentSnapshotBlock) {
            uint256 currentValue = _totalSupply;
            require(
                currentValue <= type(uint224).max,
                "VoteSnapshots: new snapshot cannot be casted safely"
            );
            _totalSupplySnapshot.snapshotBlock = _currentSnapshotBlock;
            _totalSupplySnapshot.value = uint224(currentValue);
        }
    }

    // protecting future upgradeability
    uint256[50] private __gapTotalSupplySnapshots;
}

lib/currency-1.5/contracts/currency/VoteSnapshots.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./ERC20Delegated.sol";

/**
 * Extension of ERC20Delegated to support snapshotting.
 *
 * This extension maintains a snapshot of each addresses's votes which updates on the transfer after a new snapshot is taken.
 * Only addresses that have opted into voting are snapshotted.
 */
abstract contract VoteSnapshots is ERC20Delegated {
    /// mapping of each address to it's latest snapshot of votes
    mapping(address => Snapshot) private _voteSnapshots;

    /** Construct a new instance.
     *
     * the root _policy needs to be passed down through to service ERC20BurnAndMint
     */
    constructor(
        Policy _policy,
        string memory _name,
        string memory _symbol,
        address _initialPauser
    ) ERC20Delegated(_policy, _name, _symbol, _initialPauser) {
        // call to super constructor
    }

    /**
     * Retrieve the balance for the snapshot
     *
     * @param account the address to check vote balances for
     * @return balance the balance for the acccount for the snapshot
     */
    function voteBalanceSnapshot(
        address account
    ) public view virtual returns (uint256 balance) {
        Snapshot memory _accountSnapshot = _voteSnapshots[account];

        if (
            currentSnapshotBlock != block.number &&
            _accountSnapshot.snapshotBlock < currentSnapshotBlock
        ) {
            return _voteBalances[account];
        } else {
            balance = _accountSnapshot.value;
        }
        return balance;
    }

    /**
     * Update balance snapshots for votes before the values are modified. This is implemented
     * in the _beforeVoteTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.
     * @param from the from address for the transfer
     * @param to the to address for the transfer
     * @param amount the amount of the transfer
     */
    function _beforeVoteTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual override {
        super._beforeVoteTokenTransfer(from, to, amount);

        if (from != address(0) && voter[from]) {
            _updateAccountSnapshot(from);
        }
        if (to != address(0) && voter[to]) {
            _updateAccountSnapshot(to);
        }
    }

    function _updateAccountSnapshot(address account) private {
        uint32 _currentSnapshotBlock = currentSnapshotBlock;
        // take no action during the snapshot block, only after it
        if (_currentSnapshotBlock == block.number) {
            return;
        }

        Snapshot storage snapshot = _voteSnapshots[account];
        uint256 currentValue = _voteBalances[account];

        if (snapshot.snapshotBlock < _currentSnapshotBlock) {
            require(
                currentValue <= type(uint224).max,
                "VoteSnapshots: new snapshot cannot be casted safely"
            );

            snapshot.snapshotBlock = _currentSnapshotBlock;
            snapshot.value = uint224(currentValue);
        }
    }

    // protecting future upgradeability
    uint256[50] private __gapVoteSnapshots;
}

lib/currency-1.5/contracts/governance/community/proposals/Proposal.sol

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

/**
 * @title Proposal
 * @notice Interface specification for proposals. Any proposal submitted in the
 * policy decision process must implement this interface.
 */
interface Proposal {
    /**
     * The name of the proposal.
     *
     * This should be relatively unique and descriptive.
     * @return name The name of the proposal
     */
    function name() external view returns (string memory name);

    /**
     * A longer description of what this proposal achieves.
     * @return description A longer description of what this proposal achieves.
     */
    function description() external view returns (string memory description);

    /**
     * A URL where voters can go to see the case in favour of this proposal,
     * and learn more about it.
     * @return url A URL where voters can go to see the case in favour of this proposal
     */
    function url() external view returns (string memory url);

    /**
     * Called to enact the proposal.
     *
     * This will be called from the root policy contract using delegatecall,
     * with the direct proposal address passed in as _self so that storage
     * data can be accessed if needed.
     *
     * @param _self The address of the proposal contract.
     */
    function enacted(address _self) external;
}

lib/currency-1.5/contracts/governance/monetary/CurrencyGovernance.sol

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

import "./TrustedNodes.sol";
import "./MonetaryPolicyAdapter.sol";
import "../../utils/TimeUtils.sol";
import "../../policy/Policed.sol";

/**
 * @title Trustee monetary policy decision process
 * @notice This contract oversees the voting on the currency monetary levers.
 * Trustees vote on a policy that is implemented at the conclusion of the cycle
 */
contract CurrencyGovernance is Policed, TimeUtils {
    //////////////////////////////////////////////
    /////////////////// TYPES ////////////////////
    //////////////////////////////////////////////

    // data structure for monetary policy proposals
    struct MonetaryPolicy {
        // the cycle that the proposal was submitted during
        uint256 cycle;
        // addresses to call if the proposal succeeds
        address[] targets;
        // the function signatures to call
        bytes4[] signatures;
        // the abi encoded data to call
        bytes[] calldatas;
        // the number of trustees supporting the proposal
        uint256 support;
        // the mapping of who is supporting (note, this persists past deletion)
        // this is to avoid double supporting and to confirm and record unspports
        mapping(address => bool) supporters;
        // to store a link to more information
        string description;
    }

    // struct for the array of submitted votes
    struct Vote {
        // the address of the trustee who submitted the proposal being voted for
        // proposals must be scored in ascending order of address to be accepted
        bytes32 proposalId;
        // the score of this proposal within the ballot, min recorded score is one
        // to get a score of zero, an item must be unscored
        uint256 score;
    }

    // struct for the getCurrentStage() return data type
    struct TimingData {
        // the cycle index
        // calculated by looking at how many CYCLE_LENGTHs have elapsed since the governanceStartTime
        uint256 currentCycle;
        // the governance stage
        // calculated by looking at how much time has progressed during the current cycle
        Stage currentStage;
    }

    // enum for denoting the current stage in getCurrentStage()
    enum Stage {
        Propose,
        Commit,
        Reveal
    }

    //////////////////////////////////////////////
    //////////////////// VARS ////////////////////
    //////////////////////////////////////////////

    /// this var stores the current contract that holds the trusted nodes role
    TrustedNodes public trustedNodes;

    /** this var stores the current contract that holds the enacter role */
    MonetaryPolicyAdapter public enacter;

    /** this variable tracks the start of governance
     * it is used to track the voting cycle and stage
     */
    uint256 public immutable governanceStartTime;

    // timescales
    uint256 public constant PROPOSAL_TIME = 10 days;
    uint256 public constant VOTING_TIME = 3 days;
    uint256 public constant REVEAL_TIME = 1 days;
    uint256 public constant CYCLE_LENGTH =
        PROPOSAL_TIME + VOTING_TIME + REVEAL_TIME;

    /**  start with cycle 1000 to avoid underflow and initial value issues */
    uint256 public constant START_CYCLE = 1000;

    uint256 public constant IDEMPOTENT_INFLATION_MULTIPLIER = 1e18;

    /**  max length of description field */
    uint256 public constant MAX_DESCRIPTION_DATA = 160;

    /**  max length of the targets array
     */
    uint256 public constant MAX_TARGETS = 10;

    /** mapping of proposal IDs to submitted proposals
     * proposalId hashes include the _cycle as a parameter
     */
    mapping(bytes32 => MonetaryPolicy) public proposals;
    /**  mapping of trustee addresses to cycle number to track if they have supported (and can therefore not support again) */
    mapping(address => uint256) public trusteeSupports;
    /**  mapping of trustee addresses to their most recent hash commits for voting */
    mapping(address => bytes32) public commitments;
    /**  mapping proposalIds to their voting score, accumulated during reveal */
    mapping(bytes32 => uint256) public scores;

    /**
     * @notice minimum number participating trustees required for a policy to be enacted in any given cycle
     */
    uint256 public quorum;

    /**
     * @notice number of trustees that participated this cycle
     */
    uint256 public participation;

    /** used to track the leading proposalId during the vote totalling
     * tracks the winner between reveal phases
     * is deleted on enact to ensure it can only be enacted once
     */
    bytes32 public leader;

    //////////////////////////////////////////////
    /////////////////// ERRORS ///////////////////
    //////////////////////////////////////////////

    /** setting the enacter address to the zero address stops governance */
    error NonZeroEnacterAddr();

    /**
     * setting the quorum greater than the number of trustees stops governance
     * inherently prevents the trustedNodes address from being set to the zero address
     * something to keep in mind for the case in which trustees are removed via community governance
     */
    error BadQuorum();

    /** For if a non-trustee address tries to access trustee role gated functionality */
    error TrusteeOnlyFunction();

    /** For when governance calls are made before or after their time windows for their stage */
    error WrongStage();

    /** Early finalization error
     * for when a cycle is attempted to be finalized before it finishes
     * @param requestedCycle the cycle submitted by the end user to access
     * @param currentCycle the current cycle as calculated by the contract
     */
    error CycleIncomplete(uint256 requestedCycle, uint256 currentCycle);

    /** Description length error
     * for when a proposal is submitted with too long of a description
     * @param submittedLength the length of the submitted description, to be compared against MAX_DESCRIPTION_DATA
     */
    error ExceedsMaxDescriptionSize(uint256 submittedLength);

    /** Targets length error
     * for when a proposal is submitted with too many actions or zero actions
     * @param submittedLength the length of the submitted targets array, to be compared against MAX_TARGETS and 0
     */
    error BadNumTargets(uint256 submittedLength);

    /** error for when the 3 arrays submitted for the proposal don't all have the same number of elements */
    error ProposalActionsArrayMismatch();

    /** error for when a trustee is already supporting a policy and tries to propose or support another policy */
    error SupportAlreadyGiven();

    /** error for when a trustee is not supporting a policy and tries unsupport */
    error SupportNotGiven();

    /** error for when a trustee tries unsupporting a proposal from a past cycle */
    error ProposalNotCurrent();

    /** error for when a proposal is submitted that's a total duplicate of an existing one */
    error DuplicateProposal();

    /** error for when a proposal is supported that hasn't actually been proposed */
    error NoSuchProposal();

    /** error for when a reveal is submitted with no votes */
    error CannotVoteEmpty();

    /** error for when a trustee with a commmitment tries to abstain */
    error NoAbstainWithCommit();

    /** error for when a reveal is submitted for an empty commitment, usually the sign of no commit being submitted */
    error NoCommitFound();

    /** error for when the submitted vote doesn't match the stored commit */
    error CommitMismatch();

    /** error for when a proposalId in a trustee's vote is not one from the current cycle or is completely invalid
     * @param vote the vote containing the invalid proposalId
     */
    error InvalidVoteBadProposalId(Vote vote);

    /** error for when the proposalIds in a trustee's vote are not strictly increasing
     * @param prevVote the vote before the invalid vote
     * @param vote the vote with the non-increasing proposalId
     */
    error InvalidVoteBadProposalOrder(Vote prevVote, Vote vote);

    /** error for when a score in a trustee's vote is either duplicate or doesn't respect support weightings
     * @param vote the vote containing the invalid score
     */
    error InvalidVoteBadScore(Vote vote);

    /** error for when the scores for proposals are not monotonically increasing, accounting for support weighting */
    error InvalidVotesOutOfBounds();

    /** error for when the leader's score is less than the quorum */
    error QuorumNotMet();

    /** error for when enact is called, but the cycle it's called for does not match the proposal that's the current leader  */
    error EnactCycleNotCurrent();

    //////////////////////////////////////////////
    /////////////////// EVENTS ///////////////////
    //////////////////////////////////////////////

    /**
     * emits when the trustedNodes contract is changed
     * @param newTrustedNodes denotes the new trustedNodes contract address
     * @param oldTrustedNodes denotes the old trustedNodes contract address
     */
    event NewTrustedNodes(
        TrustedNodes newTrustedNodes,
        TrustedNodes oldTrustedNodes
    );

    /**
     * @notice emits when the enacter contract is changed
     * @param newEnacter denotes the new enacter contract address
     * @param oldEnacter denotes the old enacter contract address
     */
    event NewEnacter(
        MonetaryPolicyAdapter newEnacter,
        MonetaryPolicyAdapter oldEnacter
    );

    /**
     * @notice emits when setQuorum is called successfully
     * @param newQuorum the new quorum
     * @param oldQuorum the old quorum
     */
    event NewQuorum(uint256 newQuorum, uint256 oldQuorum);

    /** Tracking for proposal creation
     * emitted when a proposal is submitted to track the values
     * @param _trusteeAddress the address of the trustee that submitted the proposal
     * @param _cycle the cycle during which the proposal was submitted
     * @param id the lookup id for the proposal in the proposals mapping
     * is created via a hash of _cycle, _targets, _signatures, and _calldatas; see getProposalHash for more details
     * @param _description a string allowing the trustee to describe the proposal or link to discussions on the proposal
     */
    event ProposalCreation(
        address indexed _trusteeAddress,
        uint256 indexed _cycle,
        bytes32 id,
        string _description
    );

    /** Tracking for support actions
     * emitted when a trustee adds their support for a proposal
     * @param trustee the address of the trustee supporting
     * @param proposalId the lookup for the proposal being supported
     * @param cycle the cycle during which the support action happened
     */
    event Support(
        address indexed trustee,
        bytes32 indexed proposalId,
        uint256 indexed cycle
    );

    /** Tracking for unsupport actions
     * emitted when a trustee retracts their support for a proposal
     * @param trustee the address of the trustee unsupporting
     * @param proposalId the lookup for the proposal being unsupported
     * @param cycle the cycle during which the support action happened
     */
    event Unsupport(
        address indexed trustee,
        bytes32 indexed proposalId,
        uint256 indexed cycle
    );

    /** Tracking for removed proposals
     * emitted when the last trustee retracts their support for a proposal
     * @param proposalId the lookup for the proposal being deleted
     * @param cycle the cycle during which the unsupport deletion action happened
     */
    event ProposalDeleted(bytes32 indexed proposalId, uint256 indexed cycle);

    /** Fired when a trustee commits their vote.
     * @param trustee the trustee that committed the vote
     * @param cycle the cycle for the commitment
     */
    event VoteCommit(address indexed trustee, uint256 indexed cycle);

    /** Fired when a vote is revealed, to create a voting history for all participants.
     * Records the voter, as well as all of the parameters of the vote cast.
     * @param voter the trustee who revealed their vote
     * @param cycle the cycle when the vote was cast and counted
     * @param votes the array of Vote structs that composed the trustee's ballot
     */
    event VoteReveal(
        address indexed voter,
        uint256 indexed cycle,
        Vote[] votes
    );

    // fired when cycle participation is high enough to enact monetary policy
    event QuorumReached();

    /** Fired when an address choses to abstain
     * @param voter the address of the voter
     * @param cycle the cycle for which the voter abstained
     */
    event Abstain(address indexed voter, uint256 indexed cycle);

    /** Fired when vote results are computed, creating a permanent record of vote outcomes.
     * @param cycle the cycle for which this is the vote result
     * @param winner the proposalId for the proposal that won
     */
    event VoteResult(uint256 cycle, bytes32 winner);

    //////////////////////////////////////////////
    ////////////////// MODIFIERS /////////////////
    //////////////////////////////////////////////

    /** Restrict access to trusted nodes only.
     */
    modifier onlyTrusted() {
        if (!trustedNodes.isTrusted(msg.sender)) {
            revert TrusteeOnlyFunction();
        }
        _;
    }

    /**  for functions related to proposing monetary policy */
    modifier duringProposePhase() {
        if ((getTime() - governanceStartTime) % CYCLE_LENGTH >= PROPOSAL_TIME) {
            revert WrongStage();
        }
        _;
    }

    /** for functions related to committing votes */
    modifier duringVotePhase() {
        uint256 governanceTime = (getTime() - governanceStartTime) %
            CYCLE_LENGTH;

        if (
            governanceTime < PROPOSAL_TIME ||
            governanceTime >= PROPOSAL_TIME + VOTING_TIME
        ) {
            revert WrongStage();
        }
        _;
    }

    /** for functions related to revealing votes */
    modifier duringRevealPhase() {
        if (
            (getTime() - governanceStartTime) % CYCLE_LENGTH <
            PROPOSAL_TIME + VOTING_TIME
        ) {
            revert WrongStage();
        }
        _;
    }

    //////////////////////////////////////////////
    ///////////////// CONSTRUCTOR ////////////////
    //////////////////////////////////////////////

    /** constructor
     * @param _policy the owning policy address for the contract
     * @param _enacter the monetary policy adapter
     * @param _quorum the required quorum for enactment of monetary policy
     * @param _termStart the time the current CurrencyGovernance term starts
     */
    constructor(
        Policy _policy,
        MonetaryPolicyAdapter _enacter,
        uint256 _quorum,
        uint256 _termStart
    ) Policed(_policy) {
        _setEnacter(_enacter);
        quorum = _quorum; // can't use _setQuorum as it's not linked to trustedNodes until after initial deploy
        governanceStartTime = _termStart;
    }

    //////////////////////////////////////////////
    ////////////////// FUNCTIONS /////////////////
    //////////////////////////////////////////////

    /** setter function for trustedNodes var
     * This function is very disruptive to the currency governance process and the timing of calling it should be VERY INTENTIONAL
     * The proposal that does so should have a timing restriction on its enaction, don't just let it be enacted as soon as it passes!
     *
     * only available to the owning policy contract
     * @param _trustedNodes the value to set the new trustedNodes address to, must have enough trustees to be able to hit quorum
     */
    function setTrustedNodes(TrustedNodes _trustedNodes) external onlyPolicy {
        emit NewTrustedNodes(_trustedNodes, trustedNodes);
        _setTrustedNodes(_trustedNodes);
    }

    function _setTrustedNodes(TrustedNodes _trustedNodes) internal {
        // don't allow a new trusted nodes contract without enough trustees to hit quorum
        // also makes sure you cannot set the trusted nodes contract to an address which doesn't have a `numTrustees()` function
        if (quorum > _trustedNodes.numTrustees()) {
            revert BadQuorum();
        }
        trustedNodes = _trustedNodes;
    }

    /** setter function for enacter var
     * only available to the owning policy contract
     * @param _enacter the value to set the new enacter address to, cannot be zero
     */
    function setEnacter(MonetaryPolicyAdapter _enacter) external onlyPolicy {
        emit NewEnacter(_enacter, enacter);
        _setEnacter(_enacter);
    }

    function _setEnacter(MonetaryPolicyAdapter _enacter) internal {
        if (address(_enacter) == address(0)) {
            revert NonZeroEnacterAddr();
        }
        enacter = _enacter;
    }

    function setQuorum(uint256 _quorum) external onlyPolicy {
        emit NewQuorum(_quorum, quorum);
        _setQuorum(_quorum);
    }

    function _setQuorum(uint256 _quorum) internal {
        if (_quorum > trustedNodes.numTrustees() || _quorum == 0) {
            revert BadQuorum();
        }
        quorum = _quorum;
    }

    /** getter for timing data
     * calculates and returns the current cycle and the current stage
     * @return timingData Timin Data type of { uint256 cycle, Stage stage }
     */
    function getCurrentStage()
        public
        view
        returns (TimingData memory timingData)
    {
        uint256 timeDifference = getTime() - governanceStartTime;
        uint256 completedCycles = START_CYCLE + timeDifference / CYCLE_LENGTH;
        uint256 governanceTime = timeDifference % CYCLE_LENGTH;

        if (governanceTime < PROPOSAL_TIME) {
            return TimingData(completedCycles, Stage.Propose);
        } else if (governanceTime < PROPOSAL_TIME + VOTING_TIME) {
            return TimingData(completedCycles, Stage.Commit);
        } else {
            return TimingData(completedCycles, Stage.Reveal);
        }
    }

    /** getter for just the current cycle
     * calculates and returns, used internally
     * @return cycle the index for the currently used governance recording mappings
     */
    function getCurrentCycle() public view returns (uint256 cycle) {
        return START_CYCLE + (getTime() - governanceStartTime) / CYCLE_LENGTH;
    }

    /** propose a monetary policy
     * this function allows trustees to submit a potential monetary policy
     * if there is already a proposed monetary policy by the trustee, this overwrites it
     * @param targets array of target addresses
     * @param signatures array of signatures
     * @param calldatas array of calldata
     * @param description descrption of the monetary policy
     */
    function propose(
        address[] calldata targets,
        bytes4[] calldata signatures,
        bytes[] memory calldatas,
        string calldata description
    ) external onlyTrusted duringProposePhase {
        uint256 cycle = getCurrentCycle();
        if (!canSupport(msg.sender)) {
            revert SupportAlreadyGiven();
        }

        trusteeSupports[msg.sender] = cycle;

        uint256 descriptionLength = bytes(description).length;
        if (descriptionLength > MAX_DESCRIPTION_DATA) {
            revert ExceedsMaxDescriptionSize(descriptionLength);
        }

        uint256 numTargets = targets.length;
        if (numTargets > MAX_TARGETS || numTargets <= 0) {
            revert BadNumTargets(numTargets);
        }
        if (numTargets != signatures.length || numTargets != calldatas.length) {
            revert ProposalActionsArrayMismatch();
        }

        bytes32 proposalId = getProposalId(
            cycle,
            targets,
            signatures,
            calldatas
        );

        MonetaryPolicy storage p = proposals[proposalId];

        // THIS IS NOT A GUARANTEE FOR DUPLICATE PROPOSALS JUST A SAFEGUARD FOR OVERWRITING
        if (p.support != 0) {
            revert DuplicateProposal();
        }
        p.support = 1;
        p.supporters[msg.sender] = true;

        p.cycle = cycle;
        p.targets = targets;
        p.signatures = signatures;
        p.calldatas = calldatas;
        p.description = description;

        emit ProposalCreation(msg.sender, cycle, proposalId, description);
        emit Support(msg.sender, proposalId, cycle);
    }

    /** getter for duplicate support checks
     * the function just pulls to see if the address has supported this generation
     * doesn't check to see if the address is a trustee
     * @param _address the address to check. not msg.sender for dapp related purposes
     */
    function canSupport(address _address) public view returns (bool) {
        return trusteeSupports[_address] < getCurrentCycle();
    }

    function getProposalId(
        uint256 _cycle,
        address[] calldata _targets,
        bytes4[] calldata _signatures,
        bytes[] memory _calldatas
    ) public pure returns (bytes32) {
        return
            keccak256(
                abi.encodePacked(
                    _cycle,
                    keccak256(abi.encode(_targets, _signatures, _calldatas))
                )
            );
    }

    function getProposalTargets(
        bytes32 proposalId
    ) external view returns (address[] memory) {
        return proposals[proposalId].targets;
    }

    function getProposalSignatures(
        bytes32 proposalId
    ) external view returns (bytes4[] memory) {
        return proposals[proposalId].signatures;
    }

    function getProposalCalldatas(
        bytes32 proposalId
    ) external view returns (bytes[] memory) {
        return proposals[proposalId].calldatas;
    }

    function getProposalSupporter(
        bytes32 proposalId,
        address supporter
    ) external view returns (bool) {
        return proposals[proposalId].supporters[supporter];
    }

    /** add your support to a monetary policy
     * this function allows you to increase the support weight to an already submitted proposal
     * the submitter of a proposal default supports it
     * support for a proposal is close to equivalent of submitting a duplicate proposal to pad the ranking
     * @param proposalId the lookup ID for the proposal that's being supported
     */
    function supportProposal(
        bytes32 proposalId
    ) external onlyTrusted duringProposePhase {
        if (!canSupport(msg.sender)) {
            revert SupportAlreadyGiven();
        }

        uint256 cycle = getCurrentCycle();

        MonetaryPolicy storage p = proposals[proposalId];

        // can support the default proposal even though is doesn't get initialized
        // the support parameter is bumped by 1 for the default proposal when its vote is counted
        // cannot support future cycle default proposals
        if (proposalId != bytes32(cycle)) {
            if (p.support == 0) {
                revert NoSuchProposal();
            }
            if (p.cycle != cycle) {
                revert ProposalNotCurrent();
            }
        }

        trusteeSupports[msg.sender] = cycle;

        ++p.support;
        p.supporters[msg.sender] = true;
        emit Support(msg.sender, proposalId, getCurrentCycle());
    }

    /** removes your support to a monetary policy
     * this function allows you to reduce the support weight to an already submitted proposal
     * you must unsupport first if you currently have supported if you want to support or propose another proposal
     * the last person who unsupports the proposal deletes the proposal
     * @param proposalId the lookup ID for the proposal that's being unsupported
     */
    function unsupportProposal(
        bytes32 proposalId
    ) external onlyTrusted duringProposePhase {
        uint256 cycle = getCurrentCycle();

        MonetaryPolicy storage p = proposals[proposalId];
        uint256 support = p.support;

        if (support == 0) {
            revert NoSuchProposal();
        }
        if (!p.supporters[msg.sender]) {
            revert SupportNotGiven();
        }
        if (p.cycle != cycle && proposalId != bytes32(cycle)) {
            revert ProposalNotCurrent();
        }

        p.supporters[msg.sender] = false;

        // deleting the default proposal doesn't do anything, but you don't want to emit the event
        if (support == 1 && proposalId != bytes32(cycle)) {
            delete proposals[proposalId];
            emit ProposalDeleted(proposalId, cycle);
        } else {
            --p.support;
        }

        trusteeSupports[msg.sender] = 0;
        emit Unsupport(msg.sender, proposalId, cycle);
    }

    /** submit a vote commitment
     * this function allows trustees to submit a commit hash of their vote
     * commitment is salted so that it is a blind vote process
     * calling additional times overwrites previous commitments
     * @param _commitment the hash commit to check against when revealing
     * the structure of the commit is keccak256(abi.encode(salt, cycleIndex, msg.sender, votes)) where votes is an array of Vote structs
     */
    function commit(bytes32 _commitment) external onlyTrusted duringVotePhase {
        commitments[msg.sender] = _commitment;
        emit VoteCommit(msg.sender, getCurrentCycle());
    }

    /** signal abstainment to the protocol
     * does not count as a vote (cannot be revealed to record positive participation for a reward)
     * signals the abstainment with an event
     * due to a small quirk, forgetting to reveal your vote in the previous round requires you to first call commit with zero data
     */
    function abstain() external onlyTrusted duringVotePhase {
        if (commitments[msg.sender] != bytes32(0)) {
            revert NoAbstainWithCommit();
        }
        emit Abstain(msg.sender, getCurrentCycle());
    }

    /** reveal a committed vote
     * this function allows trustees to reveal their previously committed votes once the reveal phase is entered
     * in revealing the vote, votes are tallied, a running tally of each proposal's votes is kept in storage during this phase
     * @param _trustee the trustee's commit to try and reveal
     * trustees can obviously reveal their own commits, but this allows for a delegated reveal
     * the commit structure means that only the correct committed vote can ever be revealed, no matter who reveals it
     * reveals are attributed to this trustee
     * @param _salt the salt for the commit hash to make the vote secret
     * @param _votes the array of Vote objects { bytes32 proposal, uint256 ranking } that follows our modified Borda scheme. The votes need to be arranged in ascending order of address and ranked via the integers 1 to the number of proposals ranked.
     */
    function reveal(
        address _trustee,
        bytes32 _salt,
        Vote[] calldata _votes
    ) external duringRevealPhase {
        uint256 _cycle = getCurrentCycle();
        uint256 numVotes = _votes.length;
        if (numVotes == 0) {
            revert CannotVoteEmpty();
        }
        if (
            keccak256(abi.encode(_salt, _cycle, _trustee, _votes)) !=
            commitments[_trustee]
        ) {
            revert CommitMismatch();
        }

        // an easy way to prevent double counting votes
        delete commitments[_trustee];

        // use memory vars to store and track the changes of the leader
        bytes32 priorLeader = leader;
        if (priorLeader != 0) {
            // Check if this is a leader from a past cycle that was never enacted
            if (
                priorLeader != bytes32(_cycle) &&
                proposals[priorLeader].cycle != _cycle
            ) {
                delete participation;
                delete leader;
                priorLeader = 0;
            }
        }

        bytes32 leaderTracker = priorLeader;
        uint256 leaderRankTracker = 0;

        participation += 1;
        if (participation == quorum) {
            emit QuorumReached();
        }

        /**
         * this variable is a bitmap to check that the scores in the ballot are correct
         */
        uint256 scoreDuplicateCheck = 0;

        uint256 i = 0;
        Vote calldata firstV = _votes[0];
        bytes32 firstProposalId = firstV.proposalId;
        // the default proposal will be first every time as its identifier has so many leading zeros that the likelyhood of a proposalId having more leading zeros is astronomically small
        if (firstProposalId == bytes32(_cycle)) {
            uint256 firstScore = firstV.score;
            uint256 _support = proposals[firstProposalId].support + 1; // default proposal has one more support than recorded in storage
            if (_support > firstScore) {
                revert InvalidVoteBadScore(firstV);
            }
            // the only bad score for the duplicate check is out of bounds
            if (firstScore > 255) {
                revert InvalidVoteBadScore(firstV);
            }
            scoreDuplicateCheck +=
                (2 ** _support - 1) <<
                (firstScore - _support);
            scores[firstProposalId] += firstScore;
            // can simplify the leader rank tracker check because we know it's the first element
            if (scores[firstProposalId] >= scores[leaderTracker]) {
                leaderTracker = firstProposalId;
                leaderRankTracker = firstScore;
            }

            // make sure to skip the first element in the following loop as it has already been handled
            ++i;
        }

        for (; i < numVotes; ++i) {
            Vote calldata v = _votes[i];
            bytes32 _proposalId = v.proposalId;
            uint256 _score = v.score;
            MonetaryPolicy storage p = proposals[_proposalId];

            if (p.cycle != _cycle) {
                revert InvalidVoteBadProposalId(v);
            }
            if (i != 0 && _votes[i - 1].proposalId >= _proposalId) {
                revert InvalidVoteBadProposalOrder(_votes[i - 1], v);
            }

            uint256 _support = p.support;
            if (_support > _score) {
                revert InvalidVoteBadScore(v);
            }
            if (_score > 255) {
                revert InvalidVoteBadScore(v);
            }
            uint256 duplicateCompare = (2 ** _support - 1) <<
                (_score - _support);

            if (scoreDuplicateCheck & duplicateCompare > 0) {
                revert InvalidVoteBadScore(v);
            }

            scoreDuplicateCheck += duplicateCompare;

            // now that the scores have been ensured to respect supporting, the previous leader calculation method is still valid
            scores[_proposalId] += _score;
            if (scores[_proposalId] > scores[leaderTracker]) {
                leaderTracker = _proposalId;
                leaderRankTracker = _score;
            } else if (scores[_proposalId] == scores[leaderTracker]) {
                if (_score > leaderRankTracker) {
                    leaderTracker = _proposalId;
                    leaderRankTracker = _score;
                }
            }
        }

        // this check afterward is very important to understand
        // it makes sure that the votes have been sequentially increasing and have been respecting the support values of each proposal
        // the only way this check succeeds is if scoreDuplicate check is of the form 1111111111etc in its binary representation after all the votes from the ballot are in
        if (scoreDuplicateCheck & (scoreDuplicateCheck + 1) > 0) {
            revert InvalidVotesOutOfBounds();
        }

        // only changes the leader if the new leader is of greater score
        if (
            leaderTracker != priorLeader &&
            scores[leaderTracker] > scores[priorLeader]
        ) {
            leader = leaderTracker;
        }

        // record the trustee's vote for compensation purposes
        trustedNodes.recordVote(_trustee);

        emit VoteReveal(_trustee, _cycle, _votes);
    }

    /** send the results to the adapter for enaction
     */
    function enact() external duringProposePhase {
        uint256 _cycle = getCurrentCycle() - 1;
        uint256 _participation = participation;
        if (
            _participation < quorum &&
            _participation < trustedNodes.numTrustees()
        ) {
            revert QuorumNotMet();
        }
        bytes32 _leader = leader;

        // this ensures that this function can only be called maximum once per winning MP
        delete leader;
        // clear this variable to reset for next cycle
        delete participation;

        // the default proposal doesn't do anything
        if (_leader == bytes32(_cycle)) {
            emit VoteResult(_cycle, _leader); // included for completionist's sake, will likely never be called
            return;
        }

        MonetaryPolicy storage _winner = proposals[_leader];

        if (_winner.cycle != _cycle) {
            revert EnactCycleNotCurrent();
        }

        enacter.enact(
            _leader,
            _winner.targets,
            _winner.signatures,
            _winner.calldatas
        );

        emit VoteResult(_cycle, _leader); // will not be emittable if enact cannot be called without reverting (downstream error)
    }
}

lib/currency-1.5/contracts/governance/monetary/MonetaryPolicyAdapter.sol

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

import "../../policy/Policed.sol";
import "../../policy/Policy.sol";
import "./CurrencyGovernance.sol";

/**
 * @title Contract for managing permissions between currency governance and monetary policy levers
 * @notice This contract enacts the results of the currency governance
 * Its goal is to act as a long term address to pemission to allow execution of trustee governance and as a long term reference for event indexing of the results
 * This module can be replaced, but it eases the difficulty of the potentially more frequent changes to the CurrencyGovernance contract
 */
contract MonetaryPolicyAdapter is Policed {
    CurrencyGovernance public currencyGovernance;

    // If the currencyGovernance address is set to zero, the contract is unrecoverably ungovernable
    error NonZeroCurrencyGovernanceAddr();

    // For if a non-currencyGovernance address tries to access currencyGovernance role gated functionality
    error CurrencyGovernanceOnlyFunction();

    /**
     * error for when a part of enacting a policy reverts
     */
    error FailedPolicy();

    /**
     * emits when the currencyGovernance contract is changed
     * @param newCurrencyGovernance denotes the new currencyGovernance contract address
     * @param oldCurrencyGovernance denotes the old currencyGovernance contract address
     */
    event NewCurrencyGovernance(
        CurrencyGovernance newCurrencyGovernance,
        CurrencyGovernance oldCurrencyGovernance
    );

    /**
     * emits when enaction happens to keep record of enaction
     * @param proposalId the proposal lookup that got successfully enacted
     * @param currencyGovernance the CurrencyGovernance contract where you can look up the proposal calldata
     */
    event EnactedMonetaryPolicy(
        bytes32 proposalId,
        CurrencyGovernance currencyGovernance
    );

    /** Restrict method access to the root policy instance only.
     */
    modifier onlyCurrencyGovernance() {
        if (msg.sender != address(currencyGovernance)) {
            revert CurrencyGovernanceOnlyFunction();
        }
        _;
    }

    constructor(Policy _policy) Policed(_policy) {}

    /** setter function for currencyGovernance var
     * only available to the owning policy contract
     * @param _currencyGovernance the value to set the new currencyGovernance address to, cannot be zero
     */
    function setCurrencyGovernance(
        CurrencyGovernance _currencyGovernance
    ) public onlyPolicy {
        emit NewCurrencyGovernance(_currencyGovernance, currencyGovernance);
        _setCurrencyGovernance(_currencyGovernance);
    }

    function _setCurrencyGovernance(
        CurrencyGovernance _currencyGovernance
    ) internal {
        if (address(_currencyGovernance) == address(0)) {
            revert NonZeroCurrencyGovernanceAddr();
        }
        currencyGovernance = _currencyGovernance;
    }

    function enact(
        bytes32 proposalId,
        address[] calldata targets,
        bytes4[] calldata signatures,
        bytes[] memory calldatas
    ) external virtual onlyCurrencyGovernance {
        // the array lengths have all been vetted already by the proposal-making process
        // upstream is just trusted
        for (uint256 i = 0; i < targets.length; ++i) {
            (bool success, bytes memory returnData) = targets[i].call(
                abi.encodePacked(signatures[i], calldatas[i])
            );

            // we might not actually need to fail gracefully, lets consider if reverting here is just fine
            if (!success) {
                revert FailedPolicy();
            }
        }

        emit EnactedMonetaryPolicy(proposalId, currencyGovernance);
    }
}

lib/currency-1.5/contracts/governance/monetary/TrustedNodes.sol

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

import "../../policy/Policed.sol";
import "../../currency/ECOx.sol";
import "../../utils/TimeUtils.sol";
import "./CurrencyGovernance.sol";

/**
 * @title TrustedNodes
 * @notice A registry of trusted nodes. Trusted nodes (trustees) are able to vote
 * on monetary policy and can only be added or removed using community
 * governance.
 *
 */
contract TrustedNodes is Policed, TimeUtils {
    uint256 public constant GENERATION_TIME = 14 days;

    uint256 public immutable termStart;

    uint256 public immutable termEnd;

    /** address with the currencyGovernance role */
    CurrencyGovernance public currencyGovernance;

    ECOx public immutable ecoX;

    mapping(address => uint256) public trusteeNumbers;

    address[] public trustees;

    /** voting record of each trustee
     */
    mapping(address => uint256) public votingRecord;

    /** timestamp of last withdrawal
     */
    mapping(address => uint256) private lastWithdrawals;

    /** reward earned per completed and revealed vote
     */
    uint256 public immutable voteReward;

    // error for functions gated only to the currency governance contract
    error GovernanceOnlyFunction();

    /** Redundant node trusting error
     * error for when an already trusted node tries to be trusted again
     * @param trusteeNumber the existing trustee number for the address
     */
    error NodeAlreadyTrusted(uint256 trusteeNumber);

    // error for when distrust is called but the address is already not trusted
    error DistrustNotTrusted();

    // error for when action is taken outside of the trustee term
    error InactiveTerm();

    // error for when withdraw is called but no tokens have been earned to withdraw
    error WithdrawNoTokens();

    /** Event emitted when a node added to a list of trusted nodes.
     * @param trustee the trustee being added
     */
    event TrustedNodeAddition(address indexed trustee);

    /** Event emitted when a node removed from a list of trusted nodes
     * @param trustee the trustee being removed
     */
    event TrustedNodeRemoval(address indexed trustee);

    /** Event emitted when a node removed from a list of trusted nodes
     * @param trustee the trustee whose vote was recorded
     * @param newVotingRecord the new voting record for the trustee
     */
    event VoteRecorded(address indexed trustee, uint256 newVotingRecord);

    /** Event emitted when voting rewards are redeemed
     * @param recipient the address redeeming the rewards
     * @param amount the amount being redeemed
     */
    event VotingRewardRedemption(address indexed recipient, uint256 amount);

    /** Event emitted when the currencyGovernance role changes
     * @param newRoleHolder the new holder of the currencyGovernance role
     */
    event CurrencyGovernanceChanged(address newRoleHolder);

    modifier onlyCurrencyGovernance() {
        if (msg.sender != address(currencyGovernance)) {
            revert GovernanceOnlyFunction();
        }
        _;
    }

    /** Creates a new trusted node registry, populated with some initial nodes
     * @param _policy the address of the root policy contract
     * @param _currencyGovernance the address of the currencyGovernance contract
     * @param _ecoX the address of the EcoX contract
     * @param _termStart the start time of the trustee term
     * @param _termLength the length of the trustee term
     * @param _voteReward the reward awarded to a trustee for each successfully revealed vote
     * @param _initialTrustees the initial cohort of trustees
     */
    constructor(
        Policy _policy,
        CurrencyGovernance _currencyGovernance,
        ECOx _ecoX,
        uint256 _termStart,
        uint256 _termLength,
        uint256 _voteReward,
        address[] memory _initialTrustees
    ) Policed(_policy) {
        currencyGovernance = _currencyGovernance;
        ecoX = _ecoX;
        termStart = _termStart;
        termEnd = termStart + _termLength;
        voteReward = _voteReward;
        uint256 _numTrustees = _initialTrustees.length;
        for (uint256 i = 0; i < _numTrustees; ++i) {
            _trust(_initialTrustees[i]);
        }
    }

    function getTrustees() public view returns (address[] memory _trustees) {
        return trustees;
    }

    /** Fetches the date of a trustee's last withdrawal
     * @param trustee the trustee whose last withdrawal date is being fetched
     * @return time the date of a trustee's last withdrawal
     */
    function getLastWithdrawal(
        address trustee
    ) internal view returns (uint256 time) {
        return termEnd + lastWithdrawals[trustee];
    }

    /** Changes the holder currencyGovernance role
     * @param _currencyGovernance the new currencyGovernance role holder
     */
    function updateCurrencyGovernance(
        CurrencyGovernance _currencyGovernance
    ) public onlyPolicy {
        currencyGovernance = _currencyGovernance;
        emit CurrencyGovernanceChanged(address(_currencyGovernance));
    }

    /** Grant trust to a node.
     *
     * The node is pushed to trustedNodes array.
     *
     * @param _node The node to start trusting.
     */
    function trust(address _node) external onlyPolicy {
        _trust(_node);
    }

    /** Helper for trust
     * @param _node The node to start trusting
     */
    function _trust(address _node) internal {
        if (isTrusted(_node)) {
            revert NodeAlreadyTrusted(trusteeNumbers[_node]);
        }
        trustees.push(_node);
        trusteeNumbers[_node] = trustees.length;
        emit TrustedNodeAddition(_node);
    }

    /** Removes a trustee from the set
     * THIS FUNCTION CAN AND WILL DISRUPT THE CURRENCY GOVERNANCE CYCLE IF CALLED DURING THE WRONG TIME
     * Try not to call this function during the commit or reveal part of the cycle in a way that interrupts the distrusted trustee
     *
     * Node to distrust swaped to be a last element in the trustedNodes, then deleted
     * @param _node The trustee to be removed
     */
    function distrust(address _node) external onlyPolicy {
        if (!isTrusted(_node)) {
            revert DistrustNotTrusted();
        }

        uint256 lastIndex = trustees.length - 1;
        uint256 trusteeIndex = trusteeNumbers[_node] - 1;
        if (trusteeIndex != lastIndex) {
            address lastNode = trustees[lastIndex];
            trustees[trusteeIndex] = lastNode;
            trusteeNumbers[lastNode] = trusteeIndex + 1;
        }
        delete trusteeNumbers[_node];
        trustees.pop();
        emit TrustedNodeRemoval(_node);
    }

    /** Incements the counter when the trustee reveals their vote
     * @param _who address whose vote is being recorded
     */
    function recordVote(address _who) external onlyCurrencyGovernance {
        uint256 time = getTime();
        if (time > termStart) {
            ++votingRecord[_who];
            emit VoteRecorded(_who, votingRecord[_who]);
        } else {
            revert InactiveTerm();
        }
    }

    /** Return the number of entries in trustedNodes array.
     */
    function numTrustees() external view returns (uint256) {
        return trustees.length;
    }

    /** Checks if a node address is trusted in the current cohort
     * @param _node the address whose trustee status we want to check
     */
    function isTrusted(address _node) public view returns (bool) {
        return trusteeNumbers[_node] > 0;
    }

    /** withdraws everything that can be withdrawn
     */
    function withdraw() public {
        uint256 numWithdrawals = calculateWithdrawal(msg.sender);
        if (numWithdrawals == 0) {
            revert WithdrawNoTokens();
        }
        uint256 toWithdraw = numWithdrawals * voteReward;
        lastWithdrawals[msg.sender] += numWithdrawals * GENERATION_TIME;
        votingRecord[msg.sender] -= numWithdrawals;

        if (!ecoX.transfer(msg.sender, toWithdraw)) {
            revert ECOx.TransferFailed();
        }
        emit VotingRewardRedemption(msg.sender, toWithdraw);
    }

    /** returns the amount of tokens that are currently withdrawable
     * @return amount  the amount of tokens that are currently withdrawable
     */
    function currentlyWithdrawable() public view returns (uint256 amount) {
        return voteReward * calculateWithdrawal(msg.sender);
    }

    /** helper for withdraw
     * @param withdrawer the addres fo the withdrawer
     * @return amount the amount of withdrawals for the withdrawer
     */
    function calculateWithdrawal(
        address withdrawer
    ) internal view returns (uint256 amount) {
        uint256 timeNow = getTime();
        if (timeNow < termEnd) {
            return 0;
        }

        uint256 lastWithdrawal = getLastWithdrawal(withdrawer);
        uint256 limit = (timeNow - lastWithdrawal) / GENERATION_TIME;
        uint256 numWithdrawals = limit > votingRecord[withdrawer]
            ? votingRecord[withdrawer]
            : limit;
        return numWithdrawals;
    }

    /** returns the number of tokens the sender is currently entitled to
     * which they will be able to withdraw upon vesting
     * @return amount the amount of tokens the message sender will be entitled to when fully vested
     * @return timestamp the timestamp when the message sender will be fully vested
     */
    function fullyVested()
        public
        view
        returns (uint256 amount, uint256 timestamp)
    {
        uint256 record = votingRecord[msg.sender];
        return (record * voteReward, termEnd + record * GENERATION_TIME);
    }

    /** drains all the ECOx in TrustedNodes to a recipient address
     * @param recipient the address to receive the ECOx
     */
    function sweep(address recipient, uint256 amount) public onlyPolicy {
        if (!ecoX.transfer(recipient, amount)) {
            revert ECOx.TransferFailed();
        }
    }
}

lib/currency-1.5/contracts/policy/Policed.sol

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

import "./Policy.sol";

/**
 * @title Policed Contracts
 * @notice A policed contract is any contract managed by a policy.
 */
abstract contract Policed {
    /** The address of the root policy instance overseeing this instance.
     */
    Policy public immutable policy;

    /** If the policy address is set to zero, the contract is unrecoverably ungovernable
     */
    error NonZeroPolicyAddr();

    /**
     * If this address is set to zero the contract is an unusable state
     * @param contractName the name of the contract that was given as the zero address
     */
    error NonZeroContractAddr(string contractName);

    /** For if a non-policy address tries to access policy role gated functionality
     */
    error PolicyOnlyFunction();

    /** Restrict method access to the root policy instance only.
     */
    modifier onlyPolicy() {
        if (msg.sender != address(policy)) {
            revert PolicyOnlyFunction();
        }
        _;
    }

    /** constructor
     * @param _policy the address of the owning policy contract
     */
    constructor(Policy _policy) {
        // _setPolicy(_policy);
        if (address(_policy) == address(0)) {
            revert NonZeroPolicyAddr();
        }
        policy = _policy;
    }
}

lib/currency-1.5/contracts/policy/PolicedUpgradeable.sol

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

import "./Policed.sol";

/** @title Policed Proxy Contracts
 *
 * A PolicedUpgradeable contract is any proxied contract managed by a policy.
 */
abstract contract PolicedUpgradeable is Policed, ForwardTarget {
    // storage gap covers PolicedUtils.expectedInterfaceSet
    // relevant for ECOxStaking
    uint256 private __gapPolicedUpgradeable;

    function setImplementation(address _impl) public onlyPolicy {
        _setImplementation(_impl);
    }
}

lib/currency-1.5/contracts/policy/Policy.sol

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

import "../proxy/ForwardTarget.sol";

/**
 * @title The policy contract that oversees other contracts
 * @notice Policy contracts provide a mechanism for building pluggable (after deploy)
 * governance systems for other contracts.
 */
contract Policy is ForwardTarget {
    uint256 private __gapPolicy; // to cover setters mapping

    /**
     * the contract allowed enact proposals
     */
    address public governor;

    /**
     * error for when an address tries submit proposal actions without permission
     */
    error OnlyGovernor();

    /**
     * error for when an address tries to call a pseudo-internal function
     */
    error OnlySelf();

    /**
     * for when a part of enacting a proposal reverts without a readable error
     * @param proposal the proposal address that got reverted during enaction
     */
    error FailedProposal(address proposal);

    /**
     * emits when the governor permissions are changed
     * @param oldGovernor denotes the old address whose permissions are being removed
     * @param newGovernor denotes the new address whose permissions are being added
     */
    event UpdatedGovernor(address oldGovernor, address newGovernor);

    /**
     * emits when enaction happens to keep record of enaction
     * @param proposal the proposal address that got successfully enacted
     * @param governor the contract which was the source of the proposal, source for looking up the calldata
     */
    event EnactedGovernanceProposal(address proposal, address governor);

    /**
     * Modifier for checking if the sender is a governor
     */
    modifier onlyGovernorRole() {
        if (msg.sender != governor) {
            revert OnlyGovernor();
        }
        _;
    }

    /**
     * Modifier for faux internal calls
     * needed for function to be called only during delegate call
     */
    modifier onlySelf() {
        if (msg.sender != address(this)) {
            revert OnlySelf();
        }
        _;
    }

    constructor(address _governor) {
        governor = _governor;
    }

    /**
     * initializes the governor
     */
    function initialize(
        address _self
    ) public virtual override onlyConstruction {
        super.initialize(_self);

        governor = Policy(_self).governor();
    }

    /**
     * pass the governance permissions to another address
     * @param _newGovernor the address to make the new governor
     */
    function updateGovernor(address _newGovernor) public onlySelf {
        emit UpdatedGovernor(governor, _newGovernor);
        governor = _newGovernor;
    }

    function enact(address proposal) external virtual onlyGovernorRole {
        // solhint-disable-next-line avoid-low-level-calls
        (bool _success, bytes memory returndata) = proposal.delegatecall(
            abi.encodeWithSignature("enacted(address)", proposal)
        );
        if (!_success) {
            if (returndata.length == 0) revert FailedProposal(proposal);
            assembly {
                revert(add(32, returndata), mload(returndata))
            }
        }

        emit EnactedGovernanceProposal(proposal, msg.sender);
    }

    // function required for backwards compatability of the contract interface to allow for the old governance execution call to complete
    function removeSelf(bytes32) external {}
}

lib/currency-1.5/contracts/proxy/ForwardTarget.sol

/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/* solhint-disable no-inline-assembly */

/**
 * @title Target for ForwardProxy and EcoInitializable
 */
abstract contract ForwardTarget {
    // Must match definition in ForwardProxy
    // keccak256("com.eco.ForwardProxy.target")
    uint256 private constant IMPLEMENTATION_SLOT =
        0xf86c915dad5894faca0dfa067c58fdf4307406d255ed0a65db394f82b77f53d4;

    modifier onlyConstruction() {
        require(
            implementation() == address(0),
            "Can only be called during initialization"
        );
        _;
    }

    constructor() {
        _setImplementation(address(this));
    }

    /** Storage initialization of cloned contract
     *
     * This is used to initialize the storage of the forwarded contract, and
     * should (typically) copy or repeat any work that would normally be
     * done in the constructor of the proxied contract.
     *
     * Implementations of ForwardTarget should override this function,
     * and chain to super.initialize(_self).
     *
     * @param _self The address of the original contract instance (the one being
     *              forwarded to).
     */
    function initialize(address _self) public virtual onlyConstruction {
        address _implAddress = address(ForwardTarget(_self).implementation());
        require(
            _implAddress != address(0),
            "initialization failure: nothing to implement"
        );
        _setImplementation(_implAddress);
    }

    /** Get the address of the proxy target contract.
     */
    function implementation() public view returns (address _impl) {
        assembly {
            _impl := sload(IMPLEMENTATION_SLOT)
        }
    }

    /** Set new implementation */
    function _setImplementation(address _impl) internal {
        require(implementation() != _impl, "Implementation already matching");
        assembly {
            sstore(IMPLEMENTATION_SLOT, _impl)
        }
    }
}

lib/currency-1.5/contracts/utils/StringPacker.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

// might not need this

library StringPacker {
    // takes a string of 31 or less characters and converts it to bytes32
    function pack(
        string memory unpacked
    ) internal pure returns (bytes32 packed) {
        // do not use this function in a lossy way, it will not work
        // only strings with 31 or less characters are stored in memory packed with their length value
        require(bytes(unpacked).length < 32);
        // shift the memory pointer to pack the length of the string into the high byte
        // by assigning this to the return value, the type of bytes32 means that, when returning,
        // the pointer continues to read into the string data
        assembly {
            packed := mload(add(unpacked, 31))
        }
    }

    // takes a bytes32 packed in the format above and unpacks it into a string
    function unpack(
        bytes32 packed
    ) internal pure returns (string memory unpacked) {
        // get the high byte which stores the length of the string when unpacked
        uint256 len = uint256(packed >> 248);
        // ensure that the length of the unpacked string doesn't read beyond the input value
        require(len < 32);
        // initialize the return value with the length
        unpacked = string(new bytes(len));
        // shift the pointer so that the length will be at the bottom of the word to match string encoding
        // then store the packed value
        assembly {
            // Potentially writes into unallocated memory as the length in the packed form will trail off the end
            // This is fine as there are no other relevant memory values to overwrite
            mstore(add(unpacked, 31), packed)
        }
    }
}

lib/currency-1.5/contracts/utils/TimeUtils.sol

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

/**
 * @title TimeUtils
 * @notice Utility class for time, allowing easy unit testing.
 */
abstract contract TimeUtils {
    /** Determine the current time as perceived by the policy timing contract.
     *
     * Used extensively in testing, but also useful in production for
     * determining what processes can currently be run.
     * @return blockTimeStamp The current block timestamp
     */
    function getTime() internal view returns (uint256 blockTimeStamp) {
        // solhint-disable-next-line not-rely-on-time
        return block.timestamp;
    }
}

lib/currency-1.5/node_modules/@openzeppelin/contracts/security/Pausable.sol

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

lib/currency-1.5/node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);
}

lib/currency-1.5/node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

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

lib/currency-1.5/node_modules/@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol

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

lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/Context.sol

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

lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/Counters.sol

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

lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/Strings.sol

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

pragma solidity ^0.8.0;

import "./math/Math.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @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] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}

lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/cryptography/ECDSA.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

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

lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/cryptography/EIP712.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/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);
    }
}

lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10**64) {
                value /= 10**64;
                result += 64;
            }
            if (value >= 10**32) {
                value /= 10**32;
                result += 32;
            }
            if (value >= 10**16) {
                value /= 10**16;
                result += 16;
            }
            if (value >= 10**8) {
                value /= 10**8;
                result += 8;
            }
            if (value >= 10**4) {
                value /= 10**4;
                result += 4;
            }
            if (value >= 10**2) {
                value /= 10**2;
                result += 2;
            }
            if (value >= 10**1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}

lib/op-eco/contracts/bridge/CrossDomainEnabledUpgradeable.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
// Heavily inspired by:
// @eth-optimism Contracts (last updated v0.5.40) (contracts/libraries/bridge/CrossDomainEnabled.sol)

/* Interface Imports */
import {ICrossDomainMessenger} from "@eth-optimism/contracts/libraries/bridge/ICrossDomainMessenger.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

/**
 * @title CrossDomainEnabledUpgradeable
 * @dev Helper contract for contracts performing cross-domain communications
 *
 * Compiler used: defined by inheriting contract
 */
contract CrossDomainEnabledUpgradeable is Initializable {
    // Messenger contract used to send and receive messages from the other domain.
    address public messenger;

    /**
     * Enforces that the modified function is only callable by a specific cross-domain account.
     * @param _sourceDomainAccount The only account on the originating domain which is
     *  authenticated to call this function.
     */
    modifier onlyFromCrossDomainAccount(address _sourceDomainAccount) {
        require(
            msg.sender == address(getCrossDomainMessenger()),
            "OVM_XCHAIN: messenger contract unauthenticated"
        );

        require(
            getCrossDomainMessenger().xDomainMessageSender() ==
                _sourceDomainAccount,
            "OVM_XCHAIN: wrong sender of cross-domain message"
        );
        _;
    }

    /**
     * Disable the implementation contract
     */
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /**
     * @param _messenger Address of the CrossDomainMessenger on the current layer.
     */
    function __CrossDomainEnabledUpgradeable_init(
        address _messenger
    ) public onlyInitializing {
        messenger = _messenger;
    }

    /**
     * Gets the messenger, usually from storage. This function is exposed in case a child contract
     * needs to override.
     * @return The address of the cross-domain messenger contract which should be used.
     */
    function getCrossDomainMessenger()
        internal
        virtual
        returns (ICrossDomainMessenger)
    {
        return ICrossDomainMessenger(messenger);
    }

    /**
     * Sends a message to an account on another domain
     * @param _crossDomainTarget The intended recipient on the destination domain
     * @param _message The data to send to the target (usually calldata to a function with
     *  `onlyFromCrossDomainAccount()`)
     * @param _gasLimit The gasLimit for the receipt of the message on the target domain.
     */
    function sendCrossDomainMessage(
        address _crossDomainTarget,
        uint32 _gasLimit,
        bytes memory _message
    ) internal {
        // slither-disable-next-line reentrancy-events, reentrancy-benign
        getCrossDomainMessenger().sendMessage(
            _crossDomainTarget,
            _message,
            _gasLimit
        );
    }

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

lib/op-eco/contracts/bridge/L1ECOBridge.sol

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

/* Interface Imports */
import {IL1ECOBridge} from "../interfaces/bridge/IL1ECOBridge.sol";
import {IL1ERC20Bridge} from "@eth-optimism/contracts/L1/messaging/IL1ERC20Bridge.sol";
import {IL2ECOBridge} from "../interfaces/bridge/IL2ECOBridge.sol";
import {IL2ERC20Bridge} from "@eth-optimism/contracts/L2/messaging/IL2ERC20Bridge.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IECO} from "@helix-foundation/currency/contracts/currency/IECO.sol";
import {ITransparentUpgradeableProxy} from "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";

/* Contract Imports */
import {CrossDomainEnabledUpgradeable} from "./CrossDomainEnabledUpgradeable.sol";
import {ProxyAdmin} from "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol";

/**
 * @title L1ECOBridge
 * @dev The L1 ECO Bridge is a contract which stores deposited L1 ECO
 * that is in use on L2. It synchronizes a corresponding L2 Bridge, informing it of deposits
 * and listening to it for newly finalized withdrawals.
 * It also acts as the authorized source of L1 governance decisions as seen by the L2.
 * All governance related data and decisions are passed through this contract so that the
 * L2 contracts can maintain and trust a single source of L1 messages.
 */
contract L1ECOBridge is IL1ECOBridge, CrossDomainEnabledUpgradeable {
    /**
     * @dev L2 side of the bridge
     */
    address public l2TokenBridge;

    /**
     * @dev L1 ECO address
     */
    address public l1Eco;

    /**
     * @dev L2 ECO address
     */
    address public l2Eco;

    /**
     * @dev L1 proxy admin that manages this proxy contract
     */
    ProxyAdmin public l1ProxyAdmin;

    /**
     * @dev L2 upgrader role
     */
    address public upgrader;

    /**
     * @dev Modifier requiring sender to be EOA.  This check could be bypassed by a malicious
     * contract via initcode, but it takes care of the user error we want to avoid.
     */
    modifier onlyEOA() {
        // Used to stop deposits from contracts (avoid accidentally lost tokens)
        require(msg.sender.code.length == 0, "L1ECOBridge: Account not EOA");
        _;
    }

    /**
     * @dev Modifier to check that the L1 token is the same as the one set in the constructor
     * @param _l1Token L1 token address to check
     */
    modifier isL1EcoToken(address _l1Token) {
        require(
            _l1Token == l1Eco,
            "L1ECOBridge: invalid L2 token address"
        );
        _;
    }

    /**
     * @dev Modifier to check that the L2 token is the same as the one set in the constructor
     * @param _l2Token L2 token address to check
     */
    modifier isL2EcoToken(address _l2Token) {
        require(
            _l2Token == l2Eco,
            "L1ECOBridge: invalid L2 token address"
        );
        _;
    }

    /**
     * @dev Modifier for gating upgrade functionality behind an authorized ECO protocol governace contract
     */
    modifier onlyUpgrader() {
        require(
            msg.sender == upgrader,
            "L1ECOBridge: caller not authorized to upgrade L2 contracts."
        );
        _;
    }

    /**
     * Disable the implementation contract
     * @custom:oz-upgrades-unsafe-allow constructor
     */
    constructor() {
        _disableInitializers();
    }

    /**
     * @inheritdoc IL1ECOBridge
     */
    function initialize(
        address _l1messenger,
        address _l2TokenBridge,
        address _l1Eco,
        address _l2Eco,
        address _l1ProxyAdmin,
        address _upgrader
    ) public initializer {
        CrossDomainEnabledUpgradeable.__CrossDomainEnabledUpgradeable_init(
            _l1messenger
        );
        l2TokenBridge = _l2TokenBridge;
        l1Eco = _l1Eco;
        l2Eco = _l2Eco;
        l1ProxyAdmin = ProxyAdmin(_l1ProxyAdmin);
        upgrader = _upgrader;
    }

    /**
     * @inheritdoc IL1ECOBridge
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeECO(address _impl, uint32 _l2Gas)
        external
        virtual
        onlyUpgrader
    {
        bytes memory message = abi.encodeWithSelector(
            IL2ECOBridge.upgradeECO.selector,
            _impl,
            block.number
        );

        sendCrossDomainMessage(l2TokenBridge, _l2Gas, message);
        emit UpgradeL2ECO(_impl);
    }

    /**
     * @inheritdoc IL1ECOBridge
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeECOx(address _impl, uint32 _l2Gas)
        external
        virtual
        onlyUpgrader
    {
        bytes memory message = abi.encodeWithSelector(
            IL2ECOBridge.upgradeECOx.selector,
            _impl,
            block.number
        );

        sendCrossDomainMessage(l2TokenBridge, _l2Gas, message);
        emit UpgradeL2ECOx(_impl);
    }

    /**
     * @inheritdoc IL1ECOBridge
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeL2Bridge(address _impl, uint32 _l2Gas)
        external
        virtual
        onlyUpgrader
    {
        bytes memory message = abi.encodeWithSelector(
            IL2ECOBridge.upgradeSelf.selector,
            _impl,
            block.number
        );

        sendCrossDomainMessage(l2TokenBridge, _l2Gas, message);
        emit UpgradeL2Bridge(_impl);
    }

     /**
     * @inheritdoc IL1ECOBridge
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeSelf(address _newBridgeImpl) external virtual onlyUpgrader {
        //cast to a payable address since l2EcoToken is the proxy address of a ITransparentUpgradeableProxy contract
        address payable proxyAddr = payable(address(this));

        ITransparentUpgradeableProxy proxy = ITransparentUpgradeableProxy(
            proxyAddr
        );
        l1ProxyAdmin.upgrade(proxy, _newBridgeImpl);

        emit UpgradeSelf(_newBridgeImpl);
    }

    /**
     * @inheritdoc IL1ERC20Bridge
     * @param _l1Token must be the ECO L1 token address.
     * @param _l2Gas The minimum gas limit required for an L2 address finalizing the transation
     */
    function depositERC20(
        address _l1Token,
        address _l2Token,
        uint256 _amount,
        uint32 _l2Gas,
        bytes calldata _data
    ) external virtual onlyEOA isL1EcoToken(_l1Token) isL2EcoToken(_l2Token) {
        _initiateERC20Deposit(
            _l1Token,
            _l2Token,
            msg.sender,
            msg.sender,
            _amount,
            _l2Gas,
            _data
        );
    }

    /**
     * @inheritdoc IL1ERC20Bridge
     * @param _l1Token must be the ECO L1 token address.
     * @param _l2Gas The minimum gas limit required for an L2 address finalizing the transation
     */
    function depositERC20To(
        address _l1Token,
        address _l2Token,
        address _to,
        uint256 _amount,
        uint32 _l2Gas,
        bytes calldata _data
    ) external virtual isL1EcoToken(_l1Token) isL2EcoToken(_l2Token) {
        _initiateERC20Deposit(
            _l1Token,
            _l2Token,
            msg.sender,
            _to,
            _amount,
            _l2Gas,
            _data
        );
    }

    /**
     * @inheritdoc IL1ERC20Bridge
     * @param _l1Token is always the ECO L1 token address.
     * @param _l2Token is always the ECO L2 token address.
     */
    function finalizeERC20Withdrawal(
        address _l1Token,
        address _l2Token,
        address _from,
        address _to,
        uint256 _gonsAmount,
        bytes calldata _data
    ) external onlyFromCrossDomainAccount(l2TokenBridge) {
        uint256 _amount = _gonsAmount / IECO(l1Eco).getPastLinearInflation(
            block.number
        );

        // equivalent to IECO(_l1Token).transfer(_to, _amount); but is revert safe
        bytes memory _ecoTransferMessage = abi.encodeWithSelector(
            IERC20.transfer.selector,
            _to,
            _amount
        );
        (bool success, bytes memory returnData) = _l1Token.call{value: 0}(
            _ecoTransferMessage
        );

        // make sure that the call to transfer didn't revert or return false
        if (success && abi.decode(returnData, (bool))) {
            // if successful, emit an event
            emit ERC20WithdrawalFinalized(
                _l1Token,
                _l2Token,
                _from,
                _to,
                _amount,
                _data
            );
        } else {
            // if the transfer fails, create a return tx
            bytes memory message = abi.encodeWithSelector(
                IL2ERC20Bridge.finalizeDeposit.selector,
                _l1Token,
                _l2Token,
                _to, // switched the _to and _from here to bounce back the deposit to the sender
                _from,
                _gonsAmount,
                _data
            );

            // Send message up to L1 bridge
            sendCrossDomainMessage(l2TokenBridge, 0, message);
            // Emit an event to signal success event listeners to expect failure
            emit WithdrawalFailed(
                _l1Token,
                _l2Token,
                _from,
                _to,
                _amount,
                _data
            );
        }
    }

    /**
     * @inheritdoc IL1ECOBridge
     */
    function rebase(uint32 _l2Gas) external {
        bytes memory message = abi.encodeWithSelector(
            IL2ECOBridge.rebase.selector,
            IECO(l1Eco).getPastLinearInflation(
                block.number
            ),
            block.number
        );

        sendCrossDomainMessage(l2TokenBridge, _l2Gas, message);
    }

    /**
     * @dev Performs the logic for deposits by informing the L2 ECO token
     * contract of the deposit and pulling in the L1 funds from the depositor
     *
     * @param _l1Token Address of the L1 ECO token contract
     * @param _l2Token Address of the L2 ECO token contract
     * @param _from Account to pull the deposit from on L1
     * @param _to Account to give the deposit to on L2
     * @param _amount Amount of ECO being deposited.
     * @param _l2Gas Gas limit required to complete the deposit on L2.
     * @param _data Optional data to forward to L2.
     */
    function _initiateERC20Deposit(
        address _l1Token,
        address _l2Token,
        address _from,
        address _to,
        uint256 _amount,
        uint32 _l2Gas,
        bytes calldata _data
    ) internal {
        // When a deposit is initiated on L1, the L1 Bridge transfers the funds to itself for future
        // withdrawals.

        IECO(_l1Token).transferFrom(_from, address(this), _amount);
        // gons move across the bridge, with inflation multipliers on either side to correctly scale balances
        _amount = _amount * IECO(l1Eco).getPastLinearInflation(
            block.number
        );

        // Construct calldata for _l2Token.finalizeDeposit(_to, _amount)
        bytes memory message = abi.encodeWithSelector(
            //call parent interface IL2ERC20Bridge to get the selector
            IL2ERC20Bridge.finalizeDeposit.selector,
            _l1Token,
            _l2Token,
            _from,
            _to,
            _amount,
            _data
        );

        // Send calldata into L2
        sendCrossDomainMessage(l2TokenBridge, _l2Gas, message);

        emit ERC20DepositInitiated(
            _l1Token,
            _l2Token,
            _from,
            _to,
            _amount,
            _data
        );
    }
}

lib/op-eco/contracts/interfaces/bridge/IL1ECOBridge.sol

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

import {IL1ERC20Bridge} from "@eth-optimism/contracts/L1/messaging/IL1ERC20Bridge.sol";

/**
 * @title IL1ECOBridge
 */
interface IL1ECOBridge is IL1ERC20Bridge {
    // Event for when the L2ECO token implementation is upgraded
    event UpgradeL2ECO(address _newEcoImpl);
    
    // Event for when the L2ECOx token implementation is upgraded
    event UpgradeL2ECOx(address _newEcoXImpl);

    // Event for when the L2ECOBridge token implementation is upgraded
    event UpgradeL2Bridge(address _newBridgeImpl);

    // Event for when this contract's token implementation is upgraded
    event UpgradeSelf(address _newBridgeImpl);

    // Event for when failed withdrawal needs to be u-turned
    event WithdrawalFailed(
        address indexed _l1Token,
        address indexed _l2Token,
        address indexed _from,
        address _to,
        uint256 _amount,
        bytes _data
    );

    /**
     * @param _l1messenger L1 Messenger address being used for cross-chain communications.
     * @param _l2TokenBridge L2 ECO bridge address.
     * @param _l1Eco address of L1 ECO contract.
     * @param _l2Eco address of L2 ECO contract.
     * @param _l1ProxyAdmin address of ProxyAdmin contract for the L1 Bridge.
     * @param _upgrader address that can perform upgrades.
     */
    function initialize(
        address _l1messenger,
        address _l2TokenBridge,
        address _l1Eco,
        address _l2Eco,
        address _l1ProxyAdmin,
        address _upgrader
    ) external;

    /**
     * @dev Upgrades the L2ECO token implementation address by sending
     *      a cross domain message to the L2 Bridge via the L1 Messenger
     * @param _impl L2 contract address.
     * @param _l2Gas The minimum gas limit required for an L2 address finalizing the transation
     */
    function upgradeECO(address _impl, uint32 _l2Gas) external;

    /**
     * @dev Upgrades the L2ECOx token implementation address by sending
     *      a cross domain message to the L2 Bridge via the L1 Messenger
     * @param _impl L2 contract address.
     * @param _l2Gas The minimum gas limit required for an L2 address finalizing the transation
     */
    function upgradeECOx(address _impl, uint32 _l2Gas) external;

    /**
     * @dev Upgrades the L2ECOBridge implementation address by sending
     *      a cross domain message to the L2 Bridge via the L1 Messenger
     * @param _impl L2 contract address.
     * @param _l2Gas The minimum gas limit required for an L2 address finalizing the transation
     */
    function upgradeL2Bridge(address _impl, uint32 _l2Gas) external;

    /**
     * @dev Upgrades this contract implementation by passing the new implementation address to the ProxyAdmin.
     * @param _newBridgeImpl The new L1ECOBridge implementation address.
     */
    function upgradeSelf(address _newBridgeImpl) external;
    
    /**
     * @dev initiates the propagation of a linear rebase from L1 to L2
     * @param _l2Gas The minimum gas limit required for an L2 address finalizing the transation
     */
    function rebase(uint32 _l2Gas) external;
}

lib/op-eco/contracts/interfaces/bridge/IL2ECOBridge.sol

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

import {IL2ERC20Bridge} from "@eth-optimism/contracts/L2/messaging/IL2ERC20Bridge.sol";

/**
 * @title IL2ECOBridge
 */
interface IL2ECOBridge is IL2ERC20Bridge {
    // Event for when the inflation multiplier is set in the rebase function
    event RebaseInitiated(uint256 _inflationMultiplier);

    // Event for when the L2ECO token implementation is upgraded
    event UpgradeECOImplementation(address _newEcoImpl);

    // Event for when the L2ECOx token implementation is upgraded
    event UpgradeECOxImplementation(address _newEcoImpl);

    // Event for when the L2ECOBridge authority is transferred to a new bridge address
    event UpgradeSelf(address _newBridgeImpl);

    /**
     * @dev Initializer that sets the L2 messanger to use, L1 bridge address, the L2 token address, and the proxy admin address
     * @param _l2CrossDomainMessenger Cross-domain messenger used by this contract on L2
     * @param _l1TokenBridge Address of the L1 bridge deployed to L1 chain
     * @param _l1Eco Address of the L1 ECO token deployed to L1 chain
     * @param _l2Eco Address of the L2 ECO token deployed to L2 chain
     * @param _l2ProxyAdmin Address of the L2 proxy admin that manages the upgrade of the L2 token implementation
     */
    function initialize(
        address _l2CrossDomainMessenger,
        address _l1TokenBridge,
        address _l1Eco,
        address _l2Eco,
        address _l2ProxyAdmin
    ) external;

    /**
     * @dev Passes the inflation multiplier to the L2Eco token.
     * @param _inflationMultiplier The inflation multiplier to rebase the token with
     * @param _blockNumber The block number of the L1 call that initiated the rebase. Used to prevent replay attacks on failed rebase calls
     */
    function rebase(uint256 _inflationMultiplier, uint256 _blockNumber) external;

    /**
     * @dev Sets the L2ECO token proxy to a new implementation address for the L2ECO token.
     * @param _newEcoImpl The address of the new L2ECO token implementation
     * @param _blockNumber The block number of the L1 call that initiated the upgrade. Used to prevent replay attacks on failed upgrade calls
     */
    function upgradeECO(address _newEcoImpl, uint256 _blockNumber) external;

    /**
     * @dev Sets the L2ECO token proxy to a new implementation address for the L2ECO token.
     * @param _newEcoXImpl The address of the new L2ECOx token implementation
     * @param _blockNumber The block number of the L1 call that initiated the upgrade. Used to prevent replay attacks on failed upgrade calls
     */
    function upgradeECOx(address _newEcoXImpl, uint256 _blockNumber) external;

    /**
     * @dev Upgrades this contract implementation by passing the new implementation address to the ProxyAdmin.
     * @param _newBridgeImpl The new L2ECOBridge implementation address.
     * @param _blockNumber The block number of the L1 call that initiated the upgrade. Used to prevent replay attacks on failed upgrade calls
     */
    function upgradeSelf(address _newBridgeImpl, uint256 _blockNumber) external;
}

lib/op-eco/node_modules/@eth-optimism/contracts/L1/messaging/IL1ERC20Bridge.sol

// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.9.0;

/**
 * @title IL1ERC20Bridge
 */
interface IL1ERC20Bridge {
    /**********
     * Events *
     **********/

    event ERC20DepositInitiated(
        address indexed _l1Token,
        address indexed _l2Token,
        address indexed _from,
        address _to,
        uint256 _amount,
        bytes _data
    );

    event ERC20WithdrawalFinalized(
        address indexed _l1Token,
        address indexed _l2Token,
        address indexed _from,
        address _to,
        uint256 _amount,
        bytes _data
    );

    /********************
     * Public Functions *
     ********************/

    /**
     * @dev get the address of the corresponding L2 bridge contract.
     * @return Address of the corresponding L2 bridge contract.
     */
    function l2TokenBridge() external returns (address);

    /**
     * @dev deposit an amount of the ERC20 to the caller's balance on L2.
     * @param _l1Token Address of the L1 ERC20 we are depositing
     * @param _l2Token Address of the L1 respective L2 ERC20
     * @param _amount Amount of the ERC20 to deposit
     * @param _l2Gas Gas limit required to complete the deposit on L2.
     * @param _data Optional data to forward to L2. This data is provided
     *        solely as a convenience for external contracts. Aside from enforcing a maximum
     *        length, these contracts provide no guarantees about its content.
     */
    function depositERC20(
        address _l1Token,
        address _l2Token,
        uint256 _amount,
        uint32 _l2Gas,
        bytes calldata _data
    ) external;

    /**
     * @dev deposit an amount of ERC20 to a recipient's balance on L2.
     * @param _l1Token Address of the L1 ERC20 we are depositing
     * @param _l2Token Address of the L1 respective L2 ERC20
     * @param _to L2 address to credit the withdrawal to.
     * @param _amount Amount of the ERC20 to deposit.
     * @param _l2Gas Gas limit required to complete the deposit on L2.
     * @param _data Optional data to forward to L2. This data is provided
     *        solely as a convenience for external contracts. Aside from enforcing a maximum
     *        length, these contracts provide no guarantees about its content.
     */
    function depositERC20To(
        address _l1Token,
        address _l2Token,
        address _to,
        uint256 _amount,
        uint32 _l2Gas,
        bytes calldata _data
    ) external;

    /*************************
     * Cross-chain Functions *
     *************************/

    /**
     * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the
     * L1 ERC20 token.
     * This call will fail if the initialized withdrawal from L2 has not been finalized.
     *
     * @param _l1Token Address of L1 token to finalizeWithdrawal for.
     * @param _l2Token Address of L2 token where withdrawal was initiated.
     * @param _from L2 address initiating the transfer.
     * @param _to L1 address to credit the withdrawal to.
     * @param _amount Amount of the ERC20 to deposit.
     * @param _data Data provided by the sender on L2. This data is provided
     *   solely as a convenience for external contracts. Aside from enforcing a maximum
     *   length, these contracts provide no guarantees about its content.
     */
    function finalizeERC20Withdrawal(
        address _l1Token,
        address _l2Token,
        address _from,
        address _to,
        uint256 _amount,
        bytes calldata _data
    ) external;
}

lib/op-eco/node_modules/@eth-optimism/contracts/L2/messaging/IL2ERC20Bridge.sol

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

/**
 * @title IL2ERC20Bridge
 */
interface IL2ERC20Bridge {
    /**********
     * Events *
     **********/

    event WithdrawalInitiated(
        address indexed _l1Token,
        address indexed _l2Token,
        address indexed _from,
        address _to,
        uint256 _amount,
        bytes _data
    );

    event DepositFinalized(
        address indexed _l1Token,
        address indexed _l2Token,
        address indexed _from,
        address _to,
        uint256 _amount,
        bytes _data
    );

    event DepositFailed(
        address indexed _l1Token,
        address indexed _l2Token,
        address indexed _from,
        address _to,
        uint256 _amount,
        bytes _data
    );

    /********************
     * Public Functions *
     ********************/

    /**
     * @dev get the address of the corresponding L1 bridge contract.
     * @return Address of the corresponding L1 bridge contract.
     */
    function l1TokenBridge() external returns (address);

    /**
     * @dev initiate a withdraw of some tokens to the caller's account on L1
     * @param _l2Token Address of L2 token where withdrawal was initiated.
     * @param _amount Amount of the token to withdraw.
     * @param _l1Gas Unused, but included for potential forward compatibility considerations.
     * @param _data Optional data to forward to L1. This data is provided
     *        solely as a convenience for external contracts. Aside from enforcing a maximum
     *        length, these contracts provide no guarantees about its content.
     */
    function withdraw(
        address _l2Token,
        uint256 _amount,
        uint32 _l1Gas,
        bytes calldata _data
    ) external;

    /**
     * @dev initiate a withdraw of some token to a recipient's account on L1.
     * @param _l2Token Address of L2 token where withdrawal is initiated.
     * @param _to L1 adress to credit the withdrawal to.
     * @param _amount Amount of the token to withdraw.
     * @param _l1Gas Unused, but included for potential forward compatibility considerations.
     * @param _data Optional data to forward to L1. This data is provided
     *        solely as a convenience for external contracts. Aside from enforcing a maximum
     *        length, these contracts provide no guarantees about its content.
     */
    function withdrawTo(
        address _l2Token,
        address _to,
        uint256 _amount,
        uint32 _l1Gas,
        bytes calldata _data
    ) external;

    /*************************
     * Cross-chain Functions *
     *************************/

    /**
     * @dev Complete a deposit from L1 to L2, and credits funds to the recipient's balance of this
     * L2 token. This call will fail if it did not originate from a corresponding deposit in
     * L1StandardTokenBridge.
     * @param _l1Token Address for the l1 token this is called with
     * @param _l2Token Address for the l2 token this is called with
     * @param _from Account to pull the deposit from on L2.
     * @param _to Address to receive the withdrawal at
     * @param _amount Amount of the token to withdraw
     * @param _data Data provider by the sender on L1. This data is provided
     *        solely as a convenience for external contracts. Aside from enforcing a maximum
     *        length, these contracts provide no guarantees about its content.
     */
    function finalizeDeposit(
        address _l1Token,
        address _l2Token,
        address _from,
        address _to,
        uint256 _amount,
        bytes calldata _data
    ) external;
}

lib/op-eco/node_modules/@eth-optimism/contracts/libraries/bridge/ICrossDomainMessenger.sol

// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.9.0;

/**
 * @title ICrossDomainMessenger
 */
interface ICrossDomainMessenger {
    /**********
     * Events *
     **********/

    event SentMessage(
        address indexed target,
        address sender,
        bytes message,
        uint256 messageNonce,
        uint256 gasLimit
    );
    event RelayedMessage(bytes32 indexed msgHash);
    event FailedRelayedMessage(bytes32 indexed msgHash);

    /*************
     * Variables *
     *************/

    function xDomainMessageSender() external view returns (address);

    /********************
     * Public Functions *
     ********************/

    /**
     * Sends a cross domain message to the target messenger.
     * @param _target Target contract address.
     * @param _message Message to send to the target.
     * @param _gasLimit Gas limit for the provided message.
     */
    function sendMessage(
        address _target,
        bytes calldata _message,
        uint32 _gasLimit
    ) external;
}

lib/op-eco/node_modules/@helix-foundation/currency/contracts/currency/IECO.sol

/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../governance/IGenerationIncrease.sol";

interface IECO is IERC20, IGenerationIncrease {
    /**
     * Only available to CurrencyTimer and ECOx
     */
    function mint(address to, uint256 amount) external;

    /**
     * Only available to token holders and CurrencyTimer
     */
    function burn(address from, uint256 amount) external;

    /**
     * Returns the currentGeneration
     */
    function currentGeneration() external view returns (uint256);

    /**
     * Returns final votes of an address at the end of a blockNumber
     */
    function getPastVotes(address owner, uint256 blockNumber)
        external
        view
        returns (uint256);

    /**
     * Returns the inflation multiplier value checkpointed on or before the blockNumber
     */
    function getPastLinearInflation(uint256 blockNumber)
        external
        view
        returns (uint256);

    /**
     * Returns the final total supply at the end of the given block number
     */
    function totalSupplyAt(uint256 blockNumber) external view returns (uint256);
}

lib/op-eco/node_modules/@helix-foundation/currency/contracts/governance/IGenerationIncrease.sol

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

interface IGenerationIncrease {
    /**
     * This function is called by the TimedPolicies to update this contract on a generation increase.
     * Its presence on a contract implies that the contract's identifier is in the notificationHashes
     * array on the TimedPolicies contract.
     */
    function notifyGenerationIncrease() external;
}

lib/op-eco/node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol

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

pragma solidity ^0.8.2;

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

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

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

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

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

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

lib/op-eco/node_modules/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol

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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    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);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    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);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _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);
        }
    }
}

lib/op-eco/node_modules/@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (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 Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        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);
    }
}

lib/op-eco/node_modules/@openzeppelin/contracts/interfaces/IERC1967.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.3) (interfaces/IERC1967.sol)

pragma solidity ^0.8.0;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 *
 * _Available since v4.9._
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

lib/op-eco/node_modules/@openzeppelin/contracts/interfaces/draft-IERC1822.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.0;

/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

lib/op-eco/node_modules/@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)

pragma solidity ^0.8.0;

import "../Proxy.sol";
import "./ERC1967Upgrade.sol";

/**
 * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
 * implementation address that can be changed. This address is stored in storage in the location specified by
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
 * implementation behind the proxy.
 */
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
    /**
     * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
     *
     * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
     * function call, and allows initializing the storage of the proxy like a Solidity constructor.
     */
    constructor(address _logic, bytes memory _data) payable {
        _upgradeToAndCall(_logic, _data, false);
    }

    /**
     * @dev Returns the current implementation address.
     */
    function _implementation() internal view virtual override returns (address impl) {
        return ERC1967Upgrade._getImplementation();
    }
}

lib/op-eco/node_modules/@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.3) (proxy/ERC1967/ERC1967Upgrade.sol)

pragma solidity ^0.8.2;

import "../beacon/IBeacon.sol";
import "../../interfaces/IERC1967.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 *
 * _Available since v4.1._
 *
 * @custom:oz-upgrades-unsafe-allow delegatecall
 */
abstract contract ERC1967Upgrade is IERC1967 {
    // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev Returns the current implementation address.
     */
    function _getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
        StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Perform implementation upgrade
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeTo(address newImplementation) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);
    }

    /**
     * @dev Perform implementation upgrade with additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCall(
        address newImplementation,
        bytes memory data,
        bool forceCall
    ) internal {
        _upgradeTo(newImplementation);
        if (data.length > 0 || forceCall) {
            Address.functionDelegateCall(newImplementation, data);
        }
    }

    /**
     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCallUUPS(
        address newImplementation,
        bytes memory data,
        bool forceCall
    ) internal {
        // Upgrades from old implementations will perform a rollback test. This test requires the new
        // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
        // this special case will break upgrade paths from old UUPS implementation to new ones.
        if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
            _setImplementation(newImplementation);
        } else {
            try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
            } catch {
                revert("ERC1967Upgrade: new implementation is not UUPS");
            }
            _upgradeToAndCall(newImplementation, data, forceCall);
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     */
    function _getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        require(newAdmin != address(0), "ERC1967: new admin is the zero address");
        StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {AdminChanged} event.
     */
    function _changeAdmin(address newAdmin) internal {
        emit AdminChanged(_getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
     */
    bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function _getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
        require(
            Address.isContract(IBeacon(newBeacon).implementation()),
            "ERC1967: beacon implementation is not a contract"
        );
        StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
    }

    /**
     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
     *
     * Emits a {BeaconUpgraded} event.
     */
    function _upgradeBeaconToAndCall(
        address newBeacon,
        bytes memory data,
        bool forceCall
    ) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);
        if (data.length > 0 || forceCall) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        }
    }
}

lib/op-eco/node_modules/@openzeppelin/contracts/proxy/Proxy.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)

pragma solidity ^0.8.0;

/**
 * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
 * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
 * be specified by overriding the virtual {_implementation} function.
 *
 * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
 * different contract through the {_delegate} function.
 *
 * The success and return data of the delegated call will be returned back to the caller of the proxy.
 */
abstract contract Proxy {
    /**
     * @dev Delegates the current call to `implementation`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _delegate(address implementation) internal virtual {
        assembly {
            // Copy msg.data. We take full control of memory in this inline assembly
            // block because it will not return to Solidity code. We overwrite the
            // Solidity scratch pad at memory position 0.
            calldatacopy(0, 0, calldatasize())

            // Call the implementation.
            // out and outsize are 0 because we don't know the size yet.
            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)

            // Copy the returned data.
            returndatacopy(0, 0, returndatasize())

            switch result
            // delegatecall returns 0 on error.
            case 0 {
                revert(0, returndatasize())
            }
            default {
                return(0, returndatasize())
            }
        }
    }

    /**
     * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function
     * and {_fallback} should delegate.
     */
    function _implementation() internal view virtual returns (address);

    /**
     * @dev Delegates the current call to the address returned by `_implementation()`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _fallback() internal virtual {
        _beforeFallback();
        _delegate(_implementation());
    }

    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
     * function in the contract matches the call data.
     */
    fallback() external payable virtual {
        _fallback();
    }

    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
     * is empty.
     */
    receive() external payable virtual {
        _fallback();
    }

    /**
     * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
     * call, or as part of the Solidity `fallback` or `receive` functions.
     *
     * If overridden should call `super._beforeFallback()`.
     */
    function _beforeFallback() internal virtual {}
}

lib/op-eco/node_modules/@openzeppelin/contracts/proxy/beacon/IBeacon.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.0;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {BeaconProxy} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

lib/op-eco/node_modules/@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.3) (proxy/transparent/ProxyAdmin.sol)

pragma solidity ^0.8.0;

import "./TransparentUpgradeableProxy.sol";
import "../../access/Ownable.sol";

/**
 * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
 * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
 */
contract ProxyAdmin is Ownable {
    /**
     * @dev Returns the current implementation of `proxy`.
     *
     * Requirements:
     *
     * - This contract must be the admin of `proxy`.
     */
    function getProxyImplementation(ITransparentUpgradeableProxy proxy) public view virtual returns (address) {
        // We need to manually run the static call since the getter cannot be flagged as view
        // bytes4(keccak256("implementation()")) == 0x5c60da1b
        (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
        require(success);
        return abi.decode(returndata, (address));
    }

    /**
     * @dev Returns the current admin of `proxy`.
     *
     * Requirements:
     *
     * - This contract must be the admin of `proxy`.
     */
    function getProxyAdmin(ITransparentUpgradeableProxy proxy) public view virtual returns (address) {
        // We need to manually run the static call since the getter cannot be flagged as view
        // bytes4(keccak256("admin()")) == 0xf851a440
        (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
        require(success);
        return abi.decode(returndata, (address));
    }

    /**
     * @dev Changes the admin of `proxy` to `newAdmin`.
     *
     * Requirements:
     *
     * - This contract must be the current admin of `proxy`.
     */
    function changeProxyAdmin(ITransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
        proxy.changeAdmin(newAdmin);
    }

    /**
     * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
     *
     * Requirements:
     *
     * - This contract must be the admin of `proxy`.
     */
    function upgrade(ITransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
        proxy.upgradeTo(implementation);
    }

    /**
     * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
     * {TransparentUpgradeableProxy-upgradeToAndCall}.
     *
     * Requirements:
     *
     * - This contract must be the admin of `proxy`.
     */
    function upgradeAndCall(
        ITransparentUpgradeableProxy proxy,
        address implementation,
        bytes memory data
    ) public payable virtual onlyOwner {
        proxy.upgradeToAndCall{value: msg.value}(implementation, data);
    }
}

lib/op-eco/node_modules/@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.3) (proxy/transparent/TransparentUpgradeableProxy.sol)

pragma solidity ^0.8.0;

import "../ERC1967/ERC1967Proxy.sol";

/**
 * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}
 * does not implement this interface directly, and some of its functions are implemented by an internal dispatch
 * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not
 * include them in the ABI so this interface must be used to interact with it.
 */
interface ITransparentUpgradeableProxy is IERC1967 {
    function admin() external view returns (address);

    function implementation() external view returns (address);

    function changeAdmin(address) external;

    function upgradeTo(address) external;

    function upgradeToAndCall(address, bytes memory) external payable;
}

/**
 * @dev This contract implements a proxy that is upgradeable by an admin.
 *
 * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
 * clashing], which can potentially be used in an attack, this contract uses the
 * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
 * things that go hand in hand:
 *
 * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
 * that call matches one of the admin functions exposed by the proxy itself.
 * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
 * implementation. If the admin tries to call a function on the implementation it will fail with an error that says
 * "admin cannot fallback to proxy target".
 *
 * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
 * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
 * to sudden errors when trying to call a function from the proxy implementation.
 *
 * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
 * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
 *
 * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not
 * inherit from that interface, and instead the admin functions are implicitly implemented using a custom dispatch
 * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to
 * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the
 * implementation.
 *
 * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the compiler
 * will not check that there are no selector conflicts, due to the note above. A selector clash between any new function
 * and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This could
 * render the admin operations inaccessible, which could prevent upgradeability. Transparency may also be compromised.
 */
contract TransparentUpgradeableProxy is ERC1967Proxy {
    /**
     * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
     * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
     */
    constructor(
        address _logic,
        address admin_,
        bytes memory _data
    ) payable ERC1967Proxy(_logic, _data) {
        _changeAdmin(admin_);
    }

    /**
     * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
     *
     * CAUTION: This modifier is deprecated, as it could cause issues if the modified function has arguments, and the
     * implementation provides a function with the same selector.
     */
    modifier ifAdmin() {
        if (msg.sender == _getAdmin()) {
            _;
        } else {
            _fallback();
        }
    }

    /**
     * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior
     */
    function _fallback() internal virtual override {
        if (msg.sender == _getAdmin()) {
            bytes memory ret;
            bytes4 selector = msg.sig;
            if (selector == ITransparentUpgradeableProxy.upgradeTo.selector) {
                ret = _dispatchUpgradeTo();
            } else if (selector == ITransparentUpgradeableProxy.upgradeToAndCall.selector) {
                ret = _dispatchUpgradeToAndCall();
            } else if (selector == ITransparentUpgradeableProxy.changeAdmin.selector) {
                ret = _dispatchChangeAdmin();
            } else if (selector == ITransparentUpgradeableProxy.admin.selector) {
                ret = _dispatchAdmin();
            } else if (selector == ITransparentUpgradeableProxy.implementation.selector) {
                ret = _dispatchImplementation();
            } else {
                revert("TransparentUpgradeableProxy: admin cannot fallback to proxy target");
            }
            assembly {
                return(add(ret, 0x20), mload(ret))
            }
        } else {
            super._fallback();
        }
    }

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
     * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function _dispatchAdmin() private returns (bytes memory) {
        _requireZeroValue();

        address admin = _getAdmin();
        return abi.encode(admin);
    }

    /**
     * @dev Returns the current implementation.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
     * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
     */
    function _dispatchImplementation() private returns (bytes memory) {
        _requireZeroValue();

        address implementation = _implementation();
        return abi.encode(implementation);
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {AdminChanged} event.
     */
    function _dispatchChangeAdmin() private returns (bytes memory) {
        _requireZeroValue();

        address newAdmin = abi.decode(msg.data[4:], (address));
        _changeAdmin(newAdmin);

        return "";
    }

    /**
     * @dev Upgrade the implementation of the proxy.
     */
    function _dispatchUpgradeTo() private returns (bytes memory) {
        _requireZeroValue();

        address newImplementation = abi.decode(msg.data[4:], (address));
        _upgradeToAndCall(newImplementation, bytes(""), false);

        return "";
    }

    /**
     * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
     * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
     * proxied contract.
     */
    function _dispatchUpgradeToAndCall() private returns (bytes memory) {
        (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
        _upgradeToAndCall(newImplementation, data, true);

        return "";
    }

    /**
     * @dev Returns the current admin.
     */
    function _admin() internal view virtual returns (address) {
        return _getAdmin();
    }

    /**
     * @dev To keep this contract fully transparent, all `ifAdmin` functions must be payable. This helper is here to
     * emulate some proxy functions being non-payable while still allowing value to pass through.
     */
    function _requireZeroValue() private {
        require(msg.value == 0);
    }
}

lib/op-eco/node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);
}

lib/op-eco/node_modules/@openzeppelin/contracts/utils/Address.sol

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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    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);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    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);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _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);
        }
    }
}

lib/op-eco/node_modules/@openzeppelin/contracts/utils/Context.sol

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

lib/op-eco/node_modules/@openzeppelin/contracts/utils/StorageSlot.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris",
  "remappings": [
    ":@ensdomains/=lib/currency-1.5/node_modules/@ensdomains/",
    ":@eth-optimism/=lib/op-eco/node_modules/@eth-optimism/",
    ":@helix-foundation/=lib/currency-1.5/node_modules/@helix-foundation/",
    ":@openzeppelin-currency/=lib/currency-1.5/node_modules/@openzeppelin/",
    ":@openzeppelin-op-eco/=lib/op-eco/node_modules/@openzeppelin/",
    ":@openzeppelin/=lib/currency-1.5/node_modules/@openzeppelin/",
    ":currency-1.5/=lib/currency-1.5/contracts/",
    ":eth-gas-reporter/=lib/currency-1.5/node_modules/eth-gas-reporter/",
    ":forge-std/=lib/forge-std/src/",
    ":hardhat/=lib/currency-1.5/node_modules/hardhat/",
    ":op-eco/=lib/op-eco/contracts/",
    "lib/currency-1.5/:@helix-foundation/=lib/currency-1.5/node_modules/@helix-foundation/",
    "lib/currency-1.5/:@openzeppelin/=lib/currency-1.5/node_modules/@openzeppelin/",
    "lib/op-eco/:@helix-foundation/=lib/op-eco/node_modules/@helix-foundation/",
    "lib/op-eco/:@openzeppelin/=lib/op-eco/node_modules/@openzeppelin/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.